Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

how to calculate the time and space complexity of below python code. # Initial State graph = { ' A ' : { ' B

how to calculate the time and space complexity of below python code.
# Initial State
graph ={
'A': {'B': 2,'C': 1},
'B': {'F': 1,'G': 1,'A':2},
'C': {'D': 2,'E': 2,'A': 1,'J': 1},
'D': {'E': 1,'K': 1,'C':2},
'E': {'F': 3,'S': 2,'C': 2,'D': 1,'K': 1},
'F': {'G': 1,'B': 1,'E': 3},
'G': {'H': 1,'B': 1,'F': 1},
'H': {'S': 1,'G': 1},
'I': {'A': 2},
'J': {'C': 1},
'K': {'E': 1,'D': 1},
'S':{'E': 2,'H': 1}
}
[36]: #Code Block : Set the matrix for transition & cost (as relevant for the given
#Matrix and Cost for Hill Climbing Algorithm
import random
import numpy as np
def dict_to_matrix(graph):
nodes sorted(graph.keys())
matrix = np.zeros((len(nodes), len(nodes)))
#changes by me
#a=0
for i, node in enumerate (nodes):
for neighbor, cost in graph [node].items():
j = nodes.index(neighbor)
matrix[i, j]= cost
#a +=1
return matrix, nodes #, a
def hill_climbing(graph, start, goal):
path =[start]
while set(path)!= set(graph.keys()):
neighbors = graph[start]
if not neighbors:
return path
next_node = min(neighbors, key=neighbors.get)
if next_node in path:
unvisited_nodes = list(set(graph.keys())- set(path))
start = random.choice(unvisited_nodes)
path.append(start)
else:
path.append(next_node)
start = next_node
return path
def path_cost(graph, path):
cost =0
for i in range(len(path)1):
if path[i+1] in graph [path[i]]:
cost += graph [path[i]][path[i+1]]
else:
I
return cost
cost += float('inf') # If there is no direct path, assign infinite cost
# Random Restart Hill Climbing Algorithm dynamic Input start_node = random.choice (list(graph.keys()))
matrix, nodes = dict_to_matrix(graph)
path = hill_climbing(graph, start_node, 'S') cost = path_cost(graph, path)
print("Matrix representation of the graph:")
print(matrix)
print("Nodes in the graph:")
print(nodes)
print("Path found by the hill climbing algorithm:")
print(path)
print("Cost of the path:")
print(cost)

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Databases In Networked Information Systems 6th International Workshop Dnis 2010 Aizu Wakamatsu Japan March 2010 Proceedings Lncs 5999

Authors: Shinji Kikuchi ,Shelly Sachdeva ,Subhash Bhalla

2010th Edition

3642120377, 978-3642120374

More Books

Students also viewed these Databases questions