-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathailab_handout.py
66 lines (48 loc) · 1.13 KB
/
ailab_handout.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#Lab Assignment 1
# Write programs for introduction to Python.
#%%
#factorial
def factorial(n):
if n==1:
return n
return n*factorial(n-1)
#prime check
def isPrime(n):
for i in range(2,(int)(n**0.5)+1):
if(n%i==0):
return False
return True
# Wrtie a program to implement BFS in Python
#%%
graph = {
'a':['b','c'],
'b':['d'],
'c':['d'],
'd':[]
}
def bfs(source):
queue =[]
visited = []
visited.append(source)
queue.append(source)
while queue:
node = queue.pop(0)
print(node,end=" ")
for next in graph[node]:
if next not in visited:
queue.append(next)
visited.append(next)
#%%
#Write a program to implement DFS
graph2 = {
'a':['b','c'],
'b':['d'],
'c':['d'],
'd':[]
}
def dfs(source,visited):
print(source,end=" ")
visited.append(source)
for next in graph2[source]:
if next not in visited:
dfs(next,visited)