Answered step by step
Verified Expert Solution
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: C:
B: F: G: A:
C: D: E: A: J:
D: E: K: C:
E: F: S: C: D: K:
F: G: B: E:
G: H: B: F:
H: S: G:
I: A:
J: C:
K: E: D:
S:E: H:
: #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 dicttomatrixgraph:
nodes sortedgraphkeys
matrix npzeroslennodes lennodes
#changes by me
#a
for i node in enumerate nodes:
for neighbor, cost in graph nodeitems:
j nodes.indexneighbor
matrixi j cost
#a
return matrix, nodes # a
def hillclimbinggraph start, goal:
path start
while setpath setgraphkeys:
neighbors graphstart
if not neighbors:
return path
nextnode minneighbors keyneighbors.get
if nextnode in path:
unvisitednodes listsetgraphkeys setpath
start random.choiceunvisitednodes
path.appendstart
else:
path.appendnextnode
start nextnode
return path
def pathcostgraph path:
cost
for i in rangelenpath:
if pathi in graph pathi:
cost graph pathipathi
else:
I
return cost
cost floatinf # If there is no direct path, assign infinite cost
# Random Restart Hill Climbing Algorithm dynamic Input startnode random.choice listgraphkeys
matrix, nodes dicttomatrixgraph
path hillclimbinggraph startnode, S cost pathcostgraph path
printMatrix representation of the graph:"
printmatrix
printNodes in the graph:"
printnodes
printPath found by the hill climbing algorithm:"
printpath
printCost of the path:"
printcost
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started