Professional Documents
Culture Documents
Helping Stuff
Helping Stuff
Task 1:
Implement the graph by using dictionaries 1
graph = {
"S" : ["B","E","D"],
"A":[],
"D":[],
"C":[],
"B":["C"],
"F":["G","H"],
"H":[]
"E":["F",],
graph = {
"A":["B","E"],
"D":["C"],
"C":["A"],
"B":["E","G"],
"E":["H"],
"G":["F"],
"H":["G"],
"F":[]
}
Task 2:
Write a program to generate the path from one node to the other node?
graph = {
"A":["B","E"],
"D":["C"],
"C":["A"],
"B":["E","G"],
"E":["H"],
"G":["F"],
"H":["G"],
"F":[]
}
visited=[]
def DFS(node,Goal):
for n in graph[node]:
print(node,"-> ",end="" )
DFS(n,Goal)
print("")
DFS("A","G")
Task 3:
Program to generate all the possible paths from one node to the other node?
graph = {
"A":["B","E"],
"D":["C"],
"C":["A"],
"B":["E","G"],
"E":["H"],
"G":["F"],
"H":["G"],
"F":[]
visited=[]
def DFS(node,Goal):
for n in graph[node]:
print(node,"-> ",end="" )
DFS(n,Goal)
print("")
DFS("A","G")
Task 4:
Implement BFS, DFS,UCS, A* and Greedy DFS algorithms on given graphs.
BFS:
graph = {
"S" : ["A","D","C"],
"A":[],
"D":["B","G"],
"C":["F"],
"B":["E"],
"F":["E","G"],
"E":["G"],
visited=[]
queue=[]
def BFS(node,goal):
visited.append(node)
queue.append(node)
while queue:
m=queue.pop(0)
print(m,end=": ")
for n in graph[m]:
queue.append(n)
if n not in visited:
visited.append(n)
print(queue)
else:
break
BFS("S","G")
graph={
"A":["B","E","F"],
"E":["F","I"],
"F":["E","A","B","I"],
"I":["F","J","M","N"],
"M":["I","N"],
"J":["G","I","K"],
"N":["I","M","K"],
"B":["C","F","A"],
"C":["G","D"],
"D":["G","C","H"],
"G":["C","G","J","K","L"],
"K":["J","N","O","G"],
"O":["K","P"],
"H":["D","L"],
"L":["H","H","P"],
"P":["O","L"]
visited=[]
def DFS(node,Goal):
visited.append(node)
print(node,"->",end="" )
if node!=Goal:
for n in graph[node]:
DFS(n,Goal)
DFS("A","H")
UCS
Graph={
"S":{"A":3,"C":2,"D":2},
"A":{},
"C":{"F":1},
"D":{"B":3,"G":8},
"B":{"E":2},
"E":{"G":2},
"G":{},
"F":{"E":0,"G":4}
visited=[]
queue=[]
cost=[]
i=0
def Uniform_Cost_Search(start,goal):
queue.append(start)
visited.append(start)
cost.append(0)
while queue:
m=queue.pop(0)
for n in Graph[m]:
queue.append(n)
i=visited.index(m)
cost.append(Graph[m][n]+cost[i])
else:
x=visited.index(n)
if(cost[x]>Graph[m][n]+cost[i]):
cost[x]=(Graph[m][n]+cost[i])
visited.append(n)
if(goal in visited):
break
Uniform_Cost_Search("S","G")
Task 5:
Consider the list of characters: [‘M’,‘O’,‘H’,‘S’,‘I’,‘N’]. Show how this list is sorted using the
following algorithms:
• Bubble sort
• Selection sort
• Insertion sort
• Merge sort