Last active
October 18, 2016 09:01
-
-
Save defnull/30966587577466f853201269023aa3b7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
For a tree of nested lists with integer leaves, calculate the sum of all leaves. | |
''' | |
def recurse(root): | |
# Slow because it creates a lot of lists (generators are even slower) | |
return sum([child if isinstance(child, int) else recurse(child) for child in root]) | |
def recurse2(root): | |
# Faster because less intermediate objects are created. | |
r = 0; | |
for child in root: | |
if isinstance(child, int): | |
r += child | |
else: | |
r += recurse2(child) | |
return r | |
def stack(root): | |
# The stack approach. Faster than recurse(), slower than recurse2() | |
stack = [root] | |
result = 0 | |
while stack: | |
for node in stack.pop(): | |
if isinstance(node, int): | |
result += node | |
else: | |
stack.append(node) | |
return result | |
def mktree(root, d, n): | |
if d > 0: | |
root.extend(mktree([], d-1, n) for x in range(n)) | |
else: | |
root.extend(range(n)) | |
return root | |
# Binary tree with depth of 10 | |
tree = mktree([], 10, 2) | |
print(tree) | |
import timeit | |
print(min(timeit.repeat(lambda: recurse(tree), number=1000, repeat=10))) | |
# 1.49238705635 | |
print(min(timeit.repeat(lambda: recurse2(tree), number=1000, repeat=10))) | |
# 1.2206799984 | |
print(min(timeit.repeat(lambda: stack(tree), number=1000, repeat=10))) | |
# 1.23453998566 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment