Cleaned up the code and added comments to help understand the code. Fixed the return value to to be a list of tuples.

This commit is contained in:
2020-05-14 02:27:54 -05:00
parent 5a03db8fd5
commit ee6f91b8f6
+28 -24
View File
@@ -93,41 +93,45 @@ def shortest_path(source, target):
"""
frontier = QueueFrontier()
explored = StackFrontier()
# Create our initial node, since this is the starting node there will be no parent node.
# No need to worry about populating a movie_id.
frontier.add(Node(source, None, None))
results = [[]]
results = []
while frontier:
while not frontier.empty():
currentNode = frontier.remove()
# Is the currentNode's state (person_id) equal to the target (also a person_id)?
if currentNode.state == target:
tmp = currentNode
print("Found %s" %(people[tmp.state]))
print("Found!")
cost = 0
r = []
r.append(tmp)
index = len(results)
# If so, loop over the currentNode's parents, grandparents and so forth until we hit a node
# that has no parent node.
while tmp:
if not tmp.parent:
r.append(tmp.parent)
print("Parent found! %s" %(people[tmp.state]))
# If the parent node is None, then that means we've hit the last node in the list.
# So, we won't be adding this tmp node to the result listing as it is the source.
if not tmp.parent == None:
results.append((tmp.action, tmp.state))
tmp = tmp.parent
cost+=1
results.append(r)
print("Estimated Cost %d" %(cost))
#break
# Since we traversed the target node's parents from bottom up, so reverse the list to present the order of the connections
# in the order the caller code is expecting.
results.reverse()
print(results)
break
if not explored.contains_state(currentNode.state):
# currentNode.state has person ID.
neighbors = neighbors_for_person(currentNode.state)
explored.add(currentNode)
# currentNode.state has person ID.
neighbors = neighbors_for_person(currentNode.state)
# currentNode has been explored, so add it it the explored stack.
explored.add(currentNode)
for i in neighbors:
frontier.add(Node(i[1], currentNode, None))
for i in neighbors:
# i is a pair (movie_id, person_id), so i[i] contains the person_id.
if not explored.contains_state(i[1]):
# i[0] contains movie_id (this seemed like the best thing to use for the "action" parameter of the Node object for)
# currentNode is being set as the parent node of the new node being added to the frontier
# i[1] contains person_id
frontier.add(Node(i[1], currentNode, i[0]))
return results
return None
def person_id_for_name(name):
"""