Professional Documents
Culture Documents
Installation Procedure
The installation procedure of Python IDLE editor in windows is given below:
1. Visit https://www.python.org/ and download the latest version of python executable file.
2. Double click on python-3.7.2.exe file
3. Click on Run button
4. Add Python 3.7 to Path. Then click Install now
5. Do you want to allow the following program to make changes to this computer ?
Click YES
re
6. Set up Progress ……….
7. The Setup was successful. Click Close
ge
8. Then go to C:\Users\Online-67 select Organize → Folder and Search options → Select
Show all folders → In View select Show Hidden files and folders and drives → Click OK
9. Then go to C:\Users\Online-67\AppData\Local\Programs\Python\Python37-32
9.1. Copy the above Path
an
9.2. Go to search on your computer and type env
9.3. Click Edit the system environment variables
9.4. Click Environment Variables
9.5. Click New in user variables for online-67
av
9.5.1. Variable name : Python
9.5.2. Variable value : Paste the above copied path
9.5.3. Click OK
D
10.2. Then follow the same procedure which is in step-9. Give variable name :
Python-Scripts
11. Then go to command prompt and give commands as followed:
G
re
Check the output.
ge
an
av
, D
IT
M
G
PART A
1(a) Write a python program to print the multiplication table for the given number
re
for i in range(1, 11):
print(num, 'x', i, '=', num*i)
ge
output:
an
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
av
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
D
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
,
IT
1(b) Write a python program to check whether the given number is prime or not?
re
if flag:
print(num, "is not a prime number")
else:
ge
print(num, "is a prime number")
Output:
Enter a number: 21
21 is not a prime number
an
av
1(c) Write a python program to find factorial of the given number.
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
M
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Output:
Enter a number: 4
The factorial of 4 is 24
list1=[10,20,30]
list2=['a','b','c']
list3=["AcIT", "CSE", "AIML"]
list4=[23,45,list1,56]
print("list1=", list1)
re
print("list2=", list2)
print("list3=", list3)
print("list4=", list4)
ge
print("list operations")
print("1. Nested list:", list4)
print("2. length of list1:", len(list1))
an
print("3. list concatinate:", list1+list2+list3)
print("4. Membership operator(in, not in):", 23 in list1)
print("5. Repetition operator(*):", list1*3)
print("6. Indexing:", list2[2])
av
print("7. list slicing:", list2[1:2])
print("7. list slicing:", list2[0:2])
print("list comparision operator:", list1<[12,23,24])
D
output:
list1= [10, 20, 30]
list2= ['a', 'b', 'c']
,
IT
2(b) Write a python program to implement List methods (Add, Append, Extend &
Delete).
for i in range(0,n):
re
print("enter the elements")
num=int(input( ))
list1.append(num)
ge
print("list1=", list1)
print("list2=", list2)
an
print("1. add", list1+list2)
print("1. sum of list elements", sum(list1))
list2.append("AIML")
print("2. Append", list2)
av
list1.extend(list2)
print("3.Extend", list1)
list1.remove("VTU")
D
output:
,
IT
list1= [4, 1]
list2= ['AcIT', 'Bengaluru', 'VTU']
1. add [4, 1, 'AcIT', 'Bengaluru', 'VTU']
G
Main.py
import re
import long_responses as long
re
def message_probability(user_message, recognised_words, single_response=False,
required_words=[]):
message_certainty = 0
ge
has_required_words = True
an
for word in user_message:
if word in recognised_words:
message_certainty += 1
av
# Calculates the percent of recognised words in a user message
percentage = float(message_certainty) / float(len(recognised_words))
D
break
if has_required_words or single_response:
return int(percentage * 100)
else:
G
return 0
def check_all_messages(message):
highest_prob_list = {}
# Responses
-------------------------------------------------------------------------------------------------------
re
response('Hello!', ['hello', 'hi', 'hey', 'sup', 'heyo'], single_response=True)
response('See you!', ['bye', 'goodbye'], single_response=True)
response('I\'m doing fine, and you?', ['how', 'are', 'you', 'doing'],
ge
required_words=['how'])
response('You\'re welcome!', ['thank', 'thanks'], single_response=True)
response('Thank you!', ['i', 'love', 'code', 'palace'], required_words=['code', 'palace'])
# Longer responses
an
response(long.R_ADVICE, ['give', 'advice'], required_words=['advice'])
response(long.R_EATING, ['what', 'you', 'eat'], required_words=['you', 'eat'])
av
best_match = max(highest_prob_list, key=highest_prob_list.get)
# print(highest_prob_list)
D
response = check_all_messages(split_message)
return response
G
long_responses.py
import random
R_EATING = "I don't like eating anything because I'm a bot obviously!"
R_ADVICE = "If I were you, I would go to the internet and type exactly what you wrote
there!"
def unknown():
re
response = ["Could you please re-phrase that? ",
"...",
"Sounds about right.",
ge
"What does that mean?"][
random.randrange(4)]
return response
an
av
, D
IT
M
G
A = {0, 2, 4, 6, 8};
B = {1, 2, 3, 4, 5};
# union
print("Union :", A | B)
re
# intersection
print("Intersection :", A & B)
ge
# difference
print("Difference :", A - B)
an
# symmetric difference
print("Symmetric difference :", A ^ B)
Output:
av
Union : {0, 1, 2, 3, 4, 5, 6, 8}
Intersection : {2, 4}
Difference : {0, 8, 6}
D
my_count = my_string.count(my_substring)
G
output:
Enter a String : abacdabhfabcdf
Enter a Substring : ab
Substring occurs 3 times
dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97}
print(dict.keys())
print(dict.items())
print(dict.values())
dict.pop('Marks')
re
print(dict)
dict_new=dict.copy()
print(dict_new)
ge
dict.clear()
print(dict)
print('\nName: ', dict.get('Name'))
an
print('\nAge: ', dict.get('Age'))
dict.update({'Age':22})
print(dict)
av
output:
dict_keys(['Name', 'Rollno', 'Dept', 'Marks'])
dict_items([('Name', 'Harry'), ('Rollno', 30), ('Dept', 'cse'), ('Marks', 97)])
D
Name: None
M
Age: None
{'Age': 22}
G
PART - B
re
ge
an
av
, D
Problem
capacity = (12,8,5)
M
x = capacity[0]
y = capacity[1]
G
z = capacity[2]
memory = {}
ans = []
def get_all_states(state):
a = state[0]
b = state[1]
c = state[2]
re
memory[(a,b,c)] = 1
ge
if(a>0):
if(a+b<=y):
if( get_all_states((0,a+b,c)) ):
an
ans.append(state)
return True
else:
if( get_all_states((a-(y-b), y, c)) ):
av
ans.append(state)
return True
if(a+c<=z):
D
if( get_all_states((0,b,a+c)) ):
ans.append(state)
return True
else:
,
IT
if(b>0):
#empty b into a
G
if(a+b<=x):
if( get_all_states((a+b, 0, c)) ):
ans.append(state)
return True
else:
if( get_all_states((x, b-(x-a), c)) ):
ans.append(state)
return True
if(b+c<=z):
if( get_all_states((a, 0, b+c)) ):
ans.append(state)
return True
else:
if( get_all_states((a, b-(z-c), z)) ):
ans.append(state)
re
return True
if(c>0):
if(a+c<=x):
ge
if( get_all_states((a+c, b, 0)) ):
ans.append(state)
return True
an
else:
if( get_all_states((x, b, c-(x-a))) ):
ans.append(state)
return True
av
if(b+c<=y):
if( get_all_states((a, b+c, 0)) ):
ans.append(state)
D
return True
else:
if( get_all_states((a, y, c-(y-b))) ):
ans.append(state)
,
IT
return True
return False
initial_state = (12,0,0)
M
print("Starting work...\n")
get_all_states(initial_state)
ans.reverse()
G
for i in ans:
print(i)
Output:
Starting work...
(12, 0, 0)
(4, 8, 0)
(0, 8, 4)
(8, 0, 4)
(8, 4, 0)
(3, 4, 5)
re
(3, 8, 1)
(11, 0, 1)
(11, 1, 0)
ge
(6, 1, 5)
(6, 6, 0)
an
av
, D
IT
M
G
re
ge
from queue import PriorityQueue
v=6
graph = [[] for i in range(v)]
an
def best_first_search(actual_Src, target, n):
visited = [False] * n
av
pq = PriorityQueue()
pq.put((0, actual_Src))
visited[actual_Src] = True
D
if u == target:
break
for v, c in graph[u]:
M
if visited[v] == False:
visited[v] = True
pq.put((c, v))
G
print()
addedge(0, 1, 3)
addedge(0, 2, 6)
addedge(1, 3, 2)
addedge(1, 4, 7)
addedge(2, 5, 9)
source = 0
target = 5
re
best_first_search(source, target, v)
Output
ge
013245
an
from queue import PriorityQueue
v=6
graph = [[] for i in range(v)]
av
def best_first_search(actual_Src, target, n):
print("actual_src", actual_Src)
print("target", target)
D
print("n", n)
visited = [False] * n
pq = PriorityQueue()
pq.put((0, actual_Src))
,
IT
visited[actual_Src] = True
print("visited:", visited[actual_Src])
print("graph", graph)
M
#print("u", u)
# Displaying the path having lowest cost
print(u, end=" ")
if u == target:
break
for v, c in graph[u]:
print("visited[v]", visited[v])
if visited[v] == False:
visited[v] = True
pq.put((c, v))
print("vertex=",v,",","cost=",c)
print()
def addedge(x, y, cost):
print("x =", x,",", "y =", y)
graph[x].append((y, cost))
re
graph[y].append((x, cost))
print("graph array ...")
addedge(0, 1, 3)
ge
addedge(0, 2, 6)
addedge(1, 3, 2)
addedge(1, 4, 7)
an
addedge(2, 5, 9)
source = 0
target = 5
best_first_search(source, target, v)
av
output:
, D
IT
M
G
re
ge
def recAOStar(n):
global finalPath
print("Expanding Node:",n)
and_nodes = []
or_nodes =[]
an
av
if(n in allNodes):
if 'AND' in allNodes[n]:
and_nodes = allNodes[n]['AND']
D
if 'OR' in allNodes[n]:
or_nodes = allNodes[n]['OR']
if len(and_nodes)==0 and len(or_nodes)==0:
,
return
IT
solvable = False
marked ={}
M
min_cost_least,min_cost_group_least =
least_cost_group(and_nodes,or_nodes,{})
solvable = True
change_heuristic(n,min_cost_least)
optimal_child_group[n] = min_cost_group_least
continue
min_cost,min_cost_group = least_cost_group(and_nodes,or_nodes,marked)
is_expanded = False
if len(min_cost_group)>1:
if(min_cost_group[0] in allNodes):
is_expanded = True
recAOStar(min_cost_group[0])
if(min_cost_group[1] in allNodes):
is_expanded = True
re
recAOStar(min_cost_group[1])
else:
if(min_cost_group in allNodes):
ge
is_expanded = True
recAOStar(min_cost_group)
if is_expanded:
an
min_cost_verify, min_cost_group_verify = least_cost_group(and_nodes,
or_nodes, {})
if min_cost_group == min_cost_group_verify:
solvable = True
av
change_heuristic(n, min_cost_verify)
optimal_child_group[n] = min_cost_group
else:
D
solvable = True
change_heuristic(n, min_cost)
optimal_child_group[n] = min_cost_group
marked[min_cost_group]=1
,
IT
return heuristic(n)
node_wise_cost = {}
for node_pair in and_nodes:
if not node_pair[0] + node_pair[1] in marked:
G
cost = 0
cost = cost + heuristic(node_pair[0]) + heuristic(node_pair[1]) + 2
node_wise_cost[node_pair[0] + node_pair[1]] = cost
for node in or_nodes:
if not node in marked:
cost = 0
re
def heuristic(n):
return H_dist[n]
ge
def change_heuristic(n, cost):
H_dist[n] = cost
an
return
def print_path(node):
print(optimal_child_group[node], end="")
av
node = optimal_child_group[node]
if len(node) > 1:
if node[0] in optimal_child_group:
D
print("->", end="")
print_path(node[0])
if node[1] in optimal_child_group:
print("->", end="")
,
IT
print_path(node[1])
else:
if node in optimal_child_group:
M
print("->", end="")
print_path(node)
H_dist = {
G
'A': -1,
'B': 4,
'C': 2,
'D': 3,
'E': 6,
'F': 8,
'G': 2,
'H': 0,
'I': 0,
'J': 0
}
allNodes = {
'A': {'AND': [('C', 'D')], 'OR': ['B']},
'B': {'OR': ['E', 'F']},
'C': {'OR': ['G'], 'AND': [('H', 'I')]},
re
'D': {'OR': ['J']}
}
optimal_child_group = {}
ge
optimal_cost = recAOStar('A')
print('Nodes which gives optimal cost are')
print_path('A')
an
print('\nOptimal Cost is :: ', optimal_cost)
Output:
Expanding Node: A
av
Expanding Node: B
Expanding Node: C
Expanding Node: D
D
re
for k in range(0,N):
if board[i][k]==1 or board[k][j]==1:
return True
ge
#checking diagonally
for k in range(0,N):
for l in range(0,N):
an
if (k+l==i+j) or (k-l==i-j):
if board[k][l]==1:
return True
return False
av
def N_queens(n):
if n==0:
return True
D
for i in range(0,N):
for j in range(0,N):
if (not(attack(i,j))) and (board[i][j]!=1):
board[i][j] = 1
,
IT
if N_queens(n-1)==True:
return True
board[i][j] = 0
M
return False
N_queens(N)
for i in board:
G
print (i)
Output
re
ge
an
av
, D
IT
M
G
re
vertex.append(i)
min_path = maxsize
next_permutation=permutations(vertex)
ge
for i in next_permutation:
current_pathweight = 0
k=s
an
for j in i:
current_pathweight += graph[k][j]
k=j
current_pathweight += graph[k][s]
av
min_path = min(min_path, current_pathweight)
return min_path
D
if __name__ == "__main__":
graph = [[0, 10, 15, 20], [10, 0, 35, 25],
[15, 35, 0, 30], [20, 25, 30, 0]]
s=0
,
IT
print(travellingSalesmanProblem(graph, s))
Output:
M
80
G
global facts
global is_changed
is_changed = True
facts = [["plant","mango"],["eating","mango"],["seed","sprouts"]]
def assert_fact(fact):
re
global facts
global is_changed
if not fact in facts:
ge
facts += [fact]
is_changed = True
an
while is_changed:
is_changed = False
for A1 in facts:
if A1[0] == "seed":
av
assert_fact(["plant",A1[1]])
if A1[0] == "plant":
assert_fact(["fruit",A1[1]])
D
print(facts)
,
IT
Output :
M
G
import re
def dnf(formula):
# Base case: If the formula is a literal, return it as is
if re.fullmatch(r'[A-Z]|~[A-Z]|()""', formula):
return formula
# Recursive case: If the formula is a compound statement, convert it to DNF
re
if 'and' in formula or 'or' in formula:
# Split the formula into its component parts
parts = re.split(r'(?<=[^\w])or(?=[^\w])|(?<=[^\w])and(?=[^\w])',formula)
ge
print(f"parts: {parts}")
# Convert each part to DNF
dnf_parts = [dnf(part) for part in parts]
an
print(f"dnf_parts: {dnf_parts}")
# Combine the parts using the appropriate logical operator
if 'or' in formula:
return " or ".join(parts)
av
elif 'and' in formula:
return " and ".join(parts)
# Example usage
D
def cnf(formula):
# Base case: If the formula is a literal, return it as is
if re.fullmatch(r'[A-Z]|~[A-Z]', formula):
M
return formula
# Recursive case: If the formula is a compound statement, convert it to CNF
if 'and' in formula or 'or' in formula:
G
Output :
re
ge
an
av
, D
IT
M
G
Flames game
for i in range(len(list1)):
for j in range(len(list2)):
re
if list1[i] == list2[j]:
c = list1[i]
list1.remove(c)
ge
list2.remove(c)
list3 = list1 + ["*"] + list2
return [list3, True]
an
list3 = list1 + ["*"] + list2
return [list3, False]
if __name__ == "__main__":
av
p1 = input("Player 1 name : ")
p1 = p1.lower()
p1.replace(" ", "")
D
p1_list = list(p1)
p2 = input("Player 2 name : ")
p2 = p2.lower()
p2.replace(" ", "")
,
IT
p2_list = list(p2)
proceed = True
while proceed:
M
star_index = con_list.index("*")
p1_list = con_list[: star_index]
p2_list = con_list[star_index + 1:]
count = len(p1_list) + len(p2_list)
result = ["Friends", "Love", "Affection", "Marriage", "Enemy", "Siblings"]
while len(result) > 1:
re
ge
an
av
, D
IT
M
G