Skip to content

Instantly share code, notes, and snippets.

@vindard
Last active August 1, 2019 20:31
Show Gist options
  • Save vindard/bf05cee68aa1dd24769f3b3b83ec5d0a to your computer and use it in GitHub Desktop.
Save vindard/bf05cee68aa1dd24769f3b3b83ec5d0a to your computer and use it in GitHub Desktop.
Function that builds an n-deep binomial tree and returns the sum of the last level (practice from the PyconThailand 2018 code war)
def build_tree(depth=3):
curr_level = [1, 1]
tree=[[1], curr_level]
for i in range(depth-2):
next_level = []
for i in range(len(curr_level)-1):
next_level.append(curr_level[i] + curr_level[i+1])
next_level = [1, *next_level, 1]
curr_level = list(next_level)
tree.append(curr_level)
return tree
def run(depth):
tree = build_tree(depth)
print('\nTree sums\n---\n')
for line in tree:
print(line)
print(sum(line))
print(f"\n\n{len(tree)}th line sum is: {sum(tree[-1])}")
run(15)
import sys
def build_tree(depth):
tree = [[1]]
for i in range(depth):
print(tree[-1])
current_line = [i[0] + i[1] for i in zip(tree[-1], tree[-1][1:])]
tree.append([1, *current_line, 1])
return tree
if __name__ == "__main__":
build_tree(int(sys.argv[1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment