class Node: def __init__(self, number, parent): self.number = number self.parent = parent # get a list of all the numbers to reach this node def getPath(self): path = [self.number] parent = self.parent while parent != None: path.append(parent.number) parent = parent.parent return path def solve(start, target): currentList = [] # List of visited nodes in the previous round nextList = [Node(start, None)] # List of visited nodes in the next round (start with at least one number) seen = set([start]) # store all number that have already been seen in the previous round while nextList: # continue until the final number has reached, on each iteration the complexity grows currentList = nextList # swap the lists around nextList = [] for n in currentList: path = n.getPath() # fetch all the number that are needed to reach this point if n.number == target: # check of we have reach our target return path[::-1] # the path is in reverse at this point, so reverse it back for a in path: # for any combination of the last number and a previous number (including the last, which is the same as multiplying it by 2) newnumber = a + path[0] if newnumber <= target and newnumber not in seen: # only evaluate the new number if is is not yet seen already on a lower complexity nextList.append(Node(newnumber, n)) for n in nextList: # update the seen list seen.add(n.number) return [] # if the destination could not be reached print "path to 25 = ", solve(1, 25) print "path to 8 = ", solve(1, 8) print "path to 15 = ", solve(1, 15) print "path to 500 = ", solve(1, 500)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question