You are on page 1of 14

FACULTY OF ENGINEERING SCIENCES & TECHNOLOGY

Department of Computing
Program: BSCS

COURSE TITLE ARTIFICIAL INTELLIGENCE


SEMESTER/YEAR 7TH SEMESTER-2023

COURSE INSTRUCTOR DR SHAHEER MUHAMMAD


ASSIGNMENT NO 02
ASSIGNMENT TITLE Search Algorithms (Python implementation)

NAME TAYYABA AROOJ


CMS ID 1603-2020
SIGNATURE TAYYABA
*By signing above you attest that you have contributed to this submission and confirm that all
work you have contributed to this submission is your own work. Any suspicion of copying or
plagiarism in this work will result in an investigation of Academic Misconduct and may result in a
“0” on the work, an “F” in the course, or possibly more severe penalties.

1603-2020
BREADTH FIRST SEARCH
Code:
graph ={'Frankfurt': {'Mannheim', 'Wurzburg', 'Kassel'},
'Mannheim': {'Frankfurt', 'Karlsruhe'},
'Karlsruhe': {'Augsburg', 'Mannheim'},
'Augsburg': {'Karlsruhe', 'Munchen'},
'Wurzburg': {'Erfurt', 'Nuremberg','Frankfurt'},
'Erfurt': {'Wurzburg'},
'Nuremberg': {'Wurzburg', 'Stuttgart','Munchen'},
'Munchen': {'Nuremberg', 'Augsburg','Kassel'},
'Kassel': {'Frankfurt', 'Munchen'},
'Stuttgart': {'Nuremberg'}
}

visited = [] # List for visited nodes.


queue = [] #Initialize a queue

def bfs(visited, graph, node): #function for BFS


visited.append(node)
queue.append(node)

while queue: # Creating loop to visit each node


m = queue.pop(0)
print (m )

for neighbour in graph[m]:

1603-2020
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)

bfs(visited, graph, 'Frankfurt')

Output:

DEPTH FIRST SEARCH


CODE:
I graph ={'Frankfurt': {'Mannheim', 'Wurzburg', 'Kassel'},
'Mannheim': {'Frankfurt', 'Karlsruhe'},
'Karlsruhe': {'Augsburg', 'Mannheim'},
'Augsburg': {'Karlsruhe', 'Munchen'},
'Wurzburg': {'Erfurt', 'Nuremberg','Frankfurt'},
'Erfurt': {'Wurzburg'},
'Nuremberg': {'Wurzburg', 'Stuttgart','Munchen'},

1603-2020
'Munchen': {'Nuremberg', 'Augsburg','Kassel'},
'Kassel': {'Frankfurt', 'Munchen'},
'Stuttgart': {'Nuremberg'}
}

def dfs(graph, start, visited=None):


if visited is None:
visited = set()
visited.add(start)

print(start)

for next in graph[start] - visited:


dfs(graph, next, visited)
return visited

dfs(graph, 'Frankfurt')

OUTPUT:

1603-2020
UNIFORM COST SEARCH
CODE:
import heapq
def uniform_cost_search(graph, start, goal):
frontier = [(0, start)]
came_from = {}
cost_so_far = {start: 0}

while frontier:
current_cost, current_node = heapq.heappop(frontier)

if current_node == goal:
break

for neighbor, weight in graph[current_node].items():


new_cost = cost_so_far[current_node] + weight

1603-2020
if neighbor not in cost_so_far or new_cost < cost_so_far[neighbor]:
cost_so_far[neighbor] = new_cost
priority = new_cost
heapq.heappush(frontier, (priority, neighbor))
came_from[neighbor] = current_node

path = reconstruct_path(came_from, start, goal)


return path
def reconstruct_path(came_from, start, goal):
current = goal
path = []
while current != start:
path.insert(0, current)
current = came_from[current]
path.insert(0, start)
return path
graph = {
'Frankfurt': {'Mannheim': 85, 'Wurzburg': 217, 'Kassel': 173},
'Mannheim': {'Frankfurt': 85, 'Karlsruhe': 80},
'Karlsruhe': {'Augsburg': 250, 'Mannheim': 80},
'Augsburg': {'Karlsruhe': 250, 'Munchen': 84},
'Wurzburg': {'Erfurt': 186, 'Nuremberg': 103, 'Frankfurt': 217},
'Erfurt': {'Wurzburg': 186},
'Nuremberg': {'Wurzburg': 103, 'Stuttgart': 183, 'Munchen': 167},
'Munchen': {'Nuremberg': 167, 'Augsburg': 84, 'Kassel': 502},
'Kassel': {'Frankfurt': 173, 'Munchen': 502},
'Stuttgart': {'Nuremberg': 183}
}

1603-2020
start_node = 'Frankfurt'
goal_node = 'Munchen'

path = uniform_cost_search(graph, start_node, goal_node)


print("Shortest path:", path)

OUTPUT:

ITERATIVE DEEPENING SEARCH


CODE:
def ids(graph, start, goal):
def dfs(node, depth_limit):
if node == goal:
return [node]
if depth_limit > 0:
for neighbor in graph.get(node, []):
result = dfs(neighbor, depth_limit - 1)
if result:
return [node] + result

1603-2020
for depth_limit in range(len(graph)):
result = dfs(start, depth_limit)
if result:
return result

return None # Return None if no path is found

graph = {
'Frankfurt': {'Mannheim', 'Wurzburg', 'Kassel'},
'Mannheim': {'Frankfurt', 'Karlsruhe'},
'Karlsruhe': {'Augsburg', 'Mannheim'},
'Augsburg': {'Karlsruhe', 'Munchen'},
'Wurzburg': {'Erfurt', 'Nuremberg', 'Frankfurt'},
'Erfurt': {'Wurzburg'},
'Nuremberg': {'Wurzburg', 'Stuttgart', 'Munchen'},
'Munchen': {'Nuremberg', 'Augsburg', 'Kassel'},
'Kassel': {'Frankfurt', 'Munchen'},
'Stuttgart': {'Nuremberg'}
}

start_node = 'Frankfurt'
goal_node = 'Munchen'

result = ids(graph, start_node, goal_node)

if result:
print("Path found:", result)
else:

1603-2020
print("Path not found.")

OUTPUT:

A* SEARCH
CODE:
from typing import Dict, List, Tuple
def aStarAlgo(start_node: str, stop_node: str, graph: Dict[str, List[Tuple[str, int]]]) ->
List[str]:
open_set = {start_node}
closed_set = set()
g: Dict[str, int] = {start_node: 0}
parents: Dict[str, str] = {start_node: start_node}
f: Dict[str, int] = {start_node: g[start_node] + heuristic(start_node)}

while open_set:
n = min(open_set, key=lambda v: f[v])

if n == stop_node:

1603-2020
path = []
while n != start_node:
path.append(n)
n = parents[n]
path.append(start_node)
path.reverse()
return path

open_set.remove(n)
closed_set.add(n)

for (m, weight) in get_neighbors(n, graph):


if m in closed_set:
continue

tentative_g = g[n] + weight


if m not in open_set or tentative_g < g[m]:
parents[m] = n
g[m] = tentative_g
f[m] = g[m] + heuristic(m)
if m not in open_set:
open_set.add(m)

return []

def get_neighbors(v: str, graph: Dict[str, List[Tuple[str, int]]]) -> List[Tuple[str, int]]:
return graph.get(v, [])

def heuristic(n: str) -> int:

1603-2020
H_dist = {
'Istanbul': 600,
'Izmir': 750,
'Antalya': 500,
'Adana': 200,
'Rize': 0,
'Ankara': 300,
}
return H_dist.get(n, 0)

# Define your graph here


Graph_nodes: Dict[str, List[Tuple[str, int]]] = {
'Istanbul': [('Izmir', 8), ('Ankara', 6), ('Rize', 20)],
'Izmir': [('Antalya', 5), ('Ankara', 6)],
'Antalya': [('Ankara', 7), ('Adana', 8)],
'Adana': [('Ankara', 12), ('Rize', 13)],
'Rize': [],
'Ankara': [('Istanbul', 6), ('Izmir', 6), ('Antalya', 7), ('Adana', 12), ('Rize', 16)],
}

path = aStarAlgo('Antalya', 'Rize', Graph_nodes)

if path:
print('Path found:', path)
else:
print('Path does not exist!')

1603-2020
OUTPUT:

HILL CLIMBING
CODE:
def hill_climbing(graph, start, goal):
current_city = start
path = [current_city]
while current_city != goal:
neighbors = graph[current_city]
next_city = None
min_distance = float('inf')

for neighbor, distance in neighbors.items():


if distance < min_distance and neighbor not in path:
next_city = neighbor
min_distance = distance

1603-2020
if next_city is not None:
path.append(next_city)
current_city = next_city
else:

break

if current_city == goal:
return path
else:
return None

graph = graph = {
'Frankfurt': {'Mannheim': 85, 'Wurzburg': 217, 'Kassel': 173},
'Mannheim': {'Frankfurt': 85, 'Karlsruhe': 80},
'Karlsruhe': {'Augsburg': 250, 'Mannheim': 80},
'Augsburg': {'Karlsruhe': 250, 'Munchen': 84},
'Wurzburg': {'Erfurt': 186, 'Nuremberg': 103, 'Frankfurt': 217},
'Erfurt': {'Wurzburg': 186},
'Nuremberg': {'Wurzburg': 103, 'Stuttgart': 183, 'Munchen': 167},
'Munchen': {'Nuremberg': 167, 'Augsburg': 84, 'Kassel': 502},
'Kassel': {'Frankfurt': 173, 'Munchen': 502},
'Stuttgart': {'Nuremberg': 183}
}

start_city = 'Frankfurt'
goal_city = 'Munchen'

1603-2020
shortest_path = hill_climbing(graph, start_city, goal_city)

if shortest_path:
print(f'Shortest path from {start_city} to {goal_city}: {shortest_path}')
else:
print(f'No path found from {start_city} to {goal_city}')

OUTPUT:

1603-2020

You might also like