Last active
August 1, 2019 20:31
-
-
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)
This file contains 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
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) |
This file contains 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
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