I have been given a DFS algorithm that returns the shortest path to a goal node. It takes as arguments a graph (with all of the nodes and their paths), a starting node, a goal node, and a list of nodes that have been visited (initialized as empty). Here is the code:
def shortestPath(graph, start, end, visited = []):
path = str(start)
if start == end:
return path
shortest = None
for node in graph.childrenOf(start):
if str(node) not in visited:
visited = visited + [str(node)]
newPath = shortestPath(graph, start, end, visited)
if newPath = None:
continue
if shortest == None or len(newPath) < shortest:
shortest = newPath
if shortest != None:
path = path + shortest
else:
path = None
return path
I understand the concept of Depth First Search, but this recursion is boggling my mind. Let me know if my train of thought is at all on track and where I'm getting derailed.
So basically, the recursion occurs when newPath is assigned a value, which of course is a call to shortestPath. At that point, the recursion goes all the way down the graph until it either reaches a node with no children or the goal node. If it reaches a node with no children that isn't the goal, the base case is ignored, and the entire for loop is ignored, returning a value of none. That None then is simply passed up the chain of recursion. If it reaches the goal node, then the bottom layer of the recursion actually returns a value (path), which bubbles up to the top of the recursion.
At that point I get confused, because of what is going on with "shortest." So every time an actual value is returned for newPath, shortest is assigned that value, but then it is added to path. But let's say I have multiple paths to the goal node. I successfully find the first path, and path is equal to the sum of all of the newPaths/shortests. But then for the next recursion that successfully reaches the goal, doesn't path just keep adding on more newPaths? So won't the final result be a long list of every path I COULD visit to reach the goal node instead of the shortest path?
The path variable is local to the function. Every recursion call has its own stack frame - it is independent from the other calls). That means when the next call starts, then everything is brand new.
Related
The code below returns the kth to last element of a linked list. But I don't understand how this is, because doesn't 'for I in range(k)' return values from 0 to k?? As opposed to k to the last element?
Also in general, can someone please explain the traversal of the below, as I don't quite understand it- I do understand the fundamentals of linked list and the syntax but can't quite follow the code below. e.g. why is there a need for a runner (I'm assuming this is some sort of pointer?)
def kth_to_last(l1,k):
runner = current = l1.head
for i in range(k):
if runner is None:
return None
runner = runner.next
while runner:
current = current.next
runner = runner.next
return current
e.g. input is a linked list: a -> b -> c-> d-> None
if k is b then
output: b -> c -> d -> None
in linked list, each node only knows the next node (some times the previous one too). in that case, you cannot just "jump" k nodes forward. you need to move 1 node forward k times.
in this case, runner is the pointer for the 'current' node. its often also named "current", but since this one 'runs' over the list and doesn't really care much for its content, they named it "runner".
let say runner holds the rout, i.e. node #0
runner = runner.next
the node next to node#0 is node#1, so now runner is node#1
runner = runner.next
and now runner is node#2 and so forth. each iteration of runner = runner.next forward you 1 node.
so in order to move from node#0 to node#27, you need to write runner = runner.next 27 times, or use a loop for it.
(note: the "if" part of the loop is mostly to avoid exceptions, since you cant get the "next" of null)
a simpler way to make\understand this function is by finding the length of the list, decreasing it by k and than moving forward that many nodes.
I'm trying to walk through a Decision Tree one node at a time.
Each node can have 2-3 paths
On the nodes with 3 paths, one of the paths is always an end point, and one is sometimes and end point
We can't move backwards, but can start over
Our available functions are
getCurrentNode() #returns string of current node's path from start (ex. 'A-B-A-A-B')
getCurrentNodePaths() #returns number of possible paths from this node
startOver() #puts us back at node 0
takePath(int pathNumber) #traverse the decision tree down a desired path
I've written this pseudo code that should walk through each node recursively, but only for the 'left' most path
# Start
def walk(pathNumber):
takePath(pathNumber)
next_nodes_paths = getCurrentNodePaths()
if next_nodes_paths.length > 0:
walk(0)
startOver()
walk(0)
How can I get this to keep track of where it's been, start over, and take a new path
This creates a model of the decision tree. You can navigate to a certain Node with the select_path method. path is a string like '03231002'. You can walk over the whole tree and apply a function at each point, by using the apply_function method. There is an example for walking the whole tree.
def select_path(path):
startOver()
for pathNumber in path:
takePath(int(pathNumber))
class Node:
def __init__(self,path):
self.path = path
self.select()
self.num_children = getCurrentNodePaths().length
self.children = [Node(path+str(i)) for i in range(self.num_children)]
def select(self):
select_path(self.path)
def apply_function(self, func, recursive=False):
self.select()
func()
if recursive:
for child in self.children:
apply_function(self, func, recursive=True)
root = Node('')
#walk whole tree and apply function function:
#def function:
# pass
#root.apply_function(function, recursive=True)
Since we cannot move backwards, your approach of (recursive) depth-first search is probably difficult to handle: You can never know if a node is an end node without actually moving there, and once you have arrived, you can only make a new walk to the previous node all the way from the start.
I suggest using a breadth-first search instead (partly adopted from this example):
def walk(currentNode):
queue = []
visited = []
queue.append(currentNode)
visited.append(currentNode)
while queue:
s = queue.pop(0)
# go to node from start by following the path
startOver()
for p in s:
takePath(int(p))
for i in range(getCurrentNodePaths()):
nextNode = getCurrentNode() + str(i)
queue.append(nextNode)
visited.append(nextNode)
# Use this if you want a list of paths to end points only
# if getCurrentNodePaths() > 0:
# visited.remove(s)
print(visited)
startOver()
walk(getCurrentNode())
This will give you a list of paths to all nodes in your tree in visited.
A few notes:
A node in the queue and visited lists is assumed to be represented by its path from the start node as a string (e.g. 0, 101, 012012).
Thus, a node can be reached by just following its sequence of numbers.
Moreover, the successor nodes can be constructed by
appending the numbers within range(getCurrentNodePaths()).
I have question about postorder traversal.
The code from online is:
def postorder(tree):
if tree != None:
postorder(tree.getLeftChild())
postorder(tree.getRightChild())
print(tree.getRootVal())
i am not sure how this will ever reach the print line. Here it will keep going left until there is no left so we never get past
postorder(tree.getLeftChild())
when there is no left this line:
if tree != None:
wont be met and it will not print.
Consider a leaf, which has no children. Line by line:
if tree != None: # isn't None, so continue
postorder(tree.getLeftChild()) # will call postorder(None), which won't pass if
postorder(tree.getRightChild()) # will call postorder(None), which won't pass if
print(tree.getRootVal()) # will print
So it will reach the very bottom of the tree, and invoke the print of leaves there. Then it will recurse back up. As you noted, left subtrees will be printing before right subtrees.
Specifically about "never get past", it will. Let's consider this line, again for a leaf:
postorder(tree.getLeftChild())
For a leaf getLeftChild returns None. So that line effectively means
postorder(None)
And the if statement means that the method will just do nothing and return if None is passed.
I am trying to develop a python program to check if there is a loop in the graph when a new line is added.
I am storing different lines in a list ordered by shortest length first, and the lines are a class:
class Line():
def __init__(self,node1,node2,length):
self.node1 = node1
self.node2 = node2
self.length = int(length)
self.drawn = False
And the nodes are stored in a list:
nodes = ["A","B","C","D","E","F"]
When my program has run it stores the route as a list:
route = [class(Line),class(Line)...]
What i want it to do is to check that when a new line is added that it does not form a cycle. I plan to use a method inside of a bigger class:
something like:
def check_loop(new_line,graphs):
add new line to graph
if there is a loop in graphs:
return False
else:
return True
(sorry this is one of my first posts so the format is rubbish)
To identify if a cycle is created in a tree is pretty simple, all you need to do is pick a node and then breadth first search the entire tree from that node. If any node has been visited before by the time you reach it, then you know that there is a cycle because there was an alternative path that reached that node beside the one that you have taken.
So I want to sort a range of numbers so that the sum of every sequential number is a squared number (4,9,16,25,...) I was told I should use Depth first search but am unable to implenment it correctly, especialy the backtracking part. Is this the correct way to do this, what am I not seeing, doing wrong? Is DFS even the correct way to do this?
class Node: #Define node Object
def __init__(self, value):
self.value = value #Node "Name"
self.adjacentNodes=list() #Node Neighbours
#Set limit
limit=16
squares=list() #list for squared numbers in rang smaller than 2Xlimit
tree=list() #Tree containing nodes
path=list() #current path taken
def calculate(limit): #Population control legal squares
for i in range(1,(limit+1)):
i=i*i
if i<(limit+limit):
squares.append(i)
calculate(limit) #Populate squares list
for a in range(1,(limit+1)): #creating the nodes
newnode=Node(a)
for s in squares:
legalsum=s-a
if legalsum>0 and legalsum<limit and legalsum!=a: #zero and lower can't play,keeping non-exiting nodes out of node.adjacentNodes, don't connect to selve.
newnode.adjacentNodes.append(legalsum) #Add adjacentnode
tree.append(newnode) #add newborn to tree
for b in range(0,limit):
print tree[b].value,tree[b].adjacentNodes #Quick checkup
#Now the tree is build and can be used to search for paths.
'''
Take a node and check adjnodes
is it already visited? check path
yes-> are all nodes visited (loop over tree(currentnode).adjnodes) Maybe use len()
yes->pop last node from path and take other node -> fear for infinte loops, do I need a current node discard pile?
no -> visit next available adje node next in line from loop got from len(tree.adjn)
no-> take this as node and check adj nodes.
'''
def dfs (node):
path.append(node)
#load/check adjacent nodes
tree[node].adjacentNodes
for adjnode in tree[node-1].adjacentNodes:
if adjnode in path:
#skip to next adj node
continue
else:
print path #Quick checkup
dfs(adjnode)
dfs(8) # start with 8 since 1-16 should be {8,1,15,10,6,3,13,12,4,5,11,14,2,7,9,16}
I have no idea what you are talking about with the squares but here are some problems
def dfs (node):
#always assume the path starts with this node
path=[node]
if node == GoalState: return path #we win!!
#load/check adjacent nodes
#this line did nothing `tree[node].adjacentNodes`
for adjnode in tree[node-1].adjacentNodes:
# if adjnode in path: ****this will never be true, lets eliminate it
# #skip to next adj node
# continue
# else:
subpath = dfs(adjnode)
if subpath and subpath.endswith(GoalState):
return path + subpath #return solution
#if we get here there is no solution from this node to the goal state