Lab Manual
Lab Manual
DAVANGERE UNIVERSITY
DAVANGERE-577007, KARNATAKA
PART A:
1. write a program to implement Breadth first search using python
PART B:
1.write a program to implement hill climbing algorithm in python
2.write a program to implement a* algorithm in python
3.Implementation of Python Basic Libraries such as Math, Numpy and Scipy
4.Implementation of Python Libraries for ML application such as Pandas and
Matplotlib
5.Creation AND Loading different datasets in Python
6.Write a Python program to compute Mean, Median, Mode, Variance and
Standard deviation using datasets.
7.Implementation of Find S algorithm
8. Implementation of Candidate elimination algorithm
9.Write a program to implement Simple Linear Regression and plot the graph
10.Write a Python program to implement Stemming for a given sentence using
NLTK
PART A:
1. write a program to implement Breadth first search using python
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = []
queue = []
def bfs(visited, graph, node):
visited.append(node)
queue.append(node)
while queue:
m = queue.pop(0)
print (m, end = " ")
output:
Following is the Breadth-First Search
537248
visited = set()
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
Output:
Following is the Depth-First Search
532487
3. write a program to implement Tic-Tac-Toe game using python
board = [" " for x in range(9)]
def print_board():
row1 = "| {} | {} | {} |".format(board[0], board[1], board[2])
row2 = "| {} | {} | {} |".format(board[3], board[4], board[5])
row3 = "| {} | {} | {} |".format(board[6], board[7], board[8])
print()
print(row1)
print(row2)
print(row3)
print()
def player_move(icon):
if icon == "X":
number = 1
elif icon == "O":
number = 2
print("Your turn player {}".format(number))
choice = int(input("Enter your move (1-9): ").strip())
if board[choice - 1] == " ":
board[choice - 1] = icon
else:
print()
print("That space is taken!")
def is_victory(icon):
if (board[0] == icon and board[1] == icon and board[2] == icon) or \
(board[3] == icon and board[4] == icon and board[5] == icon) or \
(board[6] == icon and board[7] == icon and board[8] == icon) or \
(board[0] == icon and board[3] == icon and board[6] == icon) or \
(board[1] == icon and board[4] == icon and board[7] == icon) or \
(board[2] == icon and board[5] == icon and board[8] == icon) or \
(board[0] == icon and board[4] == icon and board[8] == icon) or \
(board[2] == icon and board[4] == icon and board[6] == icon):
return True
else:
return False
def is_draw():
if " " not in board:
return True
else:
return False
while True:
print_board()
player_move("X")
print_board()
if is_victory("X"):
print("X wins! Congratulations!")
break
elif is_draw():
print("It's a draw!")
break
player_move("O")
if is_victory("O"):
print_board()
print("O wins! Congratulations!")
break
elif is_draw():
print("It's a draw!")
break
Output:
| | | |
| | | |
| | | |
|X| | |
| | | |
| | | |
|X| | |
| |O| |
| | | |
|X|X| |
| |O| |
| | | |
|X|X| |
| |O| |
|O| | |
|X|X|X|
| |O| |
|O| | |
X wins! Congratulations!
def getInvCount(arr):
inv_count = 0
empty_value = -1
for i in range(0, 9):
for j in range(i + 1, 9):
if arr[j] != empty_value and arr[i] != empty_value and arr[i] > arr[j]:
inv_count += 1
return inv_count
def isSolvable(puzzle) :
return (inv_count % 2 == 0)
Output:
Solvable
Output:
Steps:
00
40
43
03
30
33
42
02
vertex.append(i)
min_path = maxsize
next_permutation=permutations(vertex)
for i in next_permutation:
current_pathweight = 0
k=s
for j in i:
current_pathweight += graph[k][j]
k=j
current_pathweight += graph[k][s]
min_path = min(min_path, current_pathweight)
return min_path
if __name__ == "__main__":
graph = [[0, 10, 15, 20], [10, 0, 35, 25],
[15, 35, 0, 30], [20, 25, 30, 0]]
s=0
print(travellingSalesmanProblem(graph, s))
Output:
80
Output:
Move disk 1 from source A to destination C
Move disk 2 from source A to destination B
Move disk 1 from source C to destination B
Move disk 3 from source A to destination C
Move disk 1 from source B to destination A
Move disk 2 from source B to destination C
Move disk 1 from source A to destination C
Move disk 4 from source A to destination B
Move disk 1 from source C to destination B
Move disk 2 from source C to destination A
Move disk 1 from source B to destination A
Move disk 3 from source C to destination B
Move disk 1 from source A to destination C
Move disk 2 from source A to destination B
Move disk 1 from source C to destination B
Output:
The steps are as follows:
step: 1 monkey slave monkey Go to boxs
step: 2 monkey take the box from box deliver to banana
step: 3 Monkey climbs up the box
step: 4 Monkey picked a banana
for j in range(0,N):
if (not(attack(i,j))) and (board[i][j]!=1):
board[i][j] = 1
if N_queens(n-1)==True:
return True
board[i][j] = 0
return False
N_queens(N)
for i in board:
print (i)
Output:
Enter the number of queens
8
[1, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 1, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 1]
[0, 0, 0, 0, 0, 1, 0, 0]
[0, 0, 1, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 1, 0]
[0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 0]
PART B:
1.write a program to implement hill climbing algorithm in python
from numpy import arange
from matplotlib import pyplot
def objective(x):
return x[0]**2.0
r_min, r_max = -5.0, 5.0
inputs = arange(r_min, r_max, 0.1)
results = [objective([x]) for x in inputs]
pyplot.plot(inputs, results)
x_optima = 0.0
pyplot.axvline(x=x_optima, ls='--', color='red')
pyplot.show()
Output:
open_set = set(start_node)
closed_set = set()
g = {}
parents = {}
g[start_node] = 0
parents[start_node] = start_node
for v in open_set:
if n == None or g[v] + heuristic(v) < g[n] + heuristic(n):
n=v
else:
if g[m] > g[n] + weight:
parents[m] = n
if m in closed_set:
closed_set.remove(m)
open_set.add(m)
if n == None:
print('Path does not exist!')
return None
if n == stop_node:
path = []
while parents[n] != n:
path.append(n)
n = parents[n]
path.append(start_node)
path.reverse()
open_set.remove(n)
closed_set.add(n)
def get_neighbors(v):
if v in Graph_nodes:
return Graph_nodes[v]
else:
return None
def heuristic(n):
H_dist = {
'A': 11,
'B': 6,
'C': 99,
'D': 1,
'E': 7,
'G': 0,
return H_dist[n]
Graph_nodes = {
'A': [('B', 2), ('E', 3)],
'B': [('C', 1),('G', 9)],
'C': None,
'E': [('D', 6)],
'D': [('G', 1)],
}
aStarAlgo('A', 'G')
Output:
Path found: ['A', 'F', 'G', 'I', 'J']
a.Math Function
import math
A = 16
print("square root of A")
print(math.sqrt(A))
Output:
square root of A 4.0
b. Numpy Function
import math
import numpy as np
A = 16
Output:
Display the original arrays and the results
Array 1: [1 2 3]
Array 2: [4 5 6]
Element-wise Addition: [5 7 9]
c. Scipy Function
import numpy as np
from scipy import linalg
two_d_array=np.array([[4,5],[3,2]])
print(linalg.det(two_d_array))
Output:
-7.0
a.Pandas
import pandas as pd
data ={"country": ["Brazil", "Russia", "India", "China", "South Africa"],
"capital": ["Brasilia", "Moscow", "New Delhi", "Beijing", "Pretoria"],
"area": [8.516, 17.10, 3.286, 9.597, 1.221],
"population": [200.4, 143.5, 1252, 1357, 52.98] }
data_table =pd.DataFrame(data)
print(data_table)
Output:
b.Matplotlib
Output:
import pandas as pd
df1 = pd.read_excel("C:\\Users\\BCA42\\Desktop\\Book1.xlsx")
df2 = pd.read_csv("C:\\Users\\BCA42\\Desktop\\Book3.csv")
Output:
6.Write a Python program to compute Mean, Median, Mode, Variance and Standard
deviation using datasets.
a.Mean
import numpy as np
list=[2, 4, 4, 4, 5, 5, 7, 9]
print(np.mean(list))
Output:
5.0
b.Median
import numpy as np
list=[2, 4, 4, 4, 5, 5, 7, 9]
print(np.median(list))
Output:
4.5
c.Mode
import statistics
list = [2, 4, 4, 4, 5, 5, 7, 9]
print(statistics.mode(list))
Output:
4
d.Variance
import numpy as np
list = [2, 4, 4, 4, 5, 5, 7, 9]
print(np.var(list))
Output:
4.0
e.Standard deviation
import numpy as np
list = [2, 4, 4, 4, 5, 5, 7, 9]
print(np.std(list))
Output:
2.0
Output:
Final hypothesis: ['?', 'Yes']
s=data[1][:-1]
g=[['?' for i in range(len(s))] for j in range(len(s))]
for i in data:
if i[-1]=="Yes":
for j in range(len(s)):
if i[j]!=s[j]:
s[j]='?'
g[j][j]='?'
elif i[-1]=="No":
for j in range(len(s)):
if i[j]!=s[j]:
g[j][j]=s[j]
else:
g[j][j]="?"
print("\nSteps of Candidate Elimination Algorithm",data.index(i)+1)
print(s)
print(g)
gh=[]
for i in g:
for j in i:
if j!='?':
gh.append(i)
break
print("\nFinal specific hypothesis:\n",s)
[['Sunny', '?', '?', '?', '?', '?'], ['?', 'Warm', '?', '?', '?', '?']]
9.Write a program to implement Simple Linear Regression and plot the graph
Output:
Estimated coefficients are :
b_0 = -0.4606060606060609
b_1 = 1.1696969696969697
10.Write a Python program to implement Stemming for a given sentence using NLTK
ps = PorterStemmer()
words = ["program", "programs", "programmer", "programming", "programmers"]
for w in words:
print(w, " : ", ps.stem(w))
Output:
program : program
programs : program
programmer : program
programming : program
programmers : program