1 # The Computer Language Shootout Benchmarks 2 # http://shootout.alioth.debian.org/ 3 # 4 # contributed by Antoine Pitrou 5 # modified by Dominique Wahli 6 7 from sys import argv 8 9 def make_tree(item, depth): 10 if depth > 0: 11 item2 = 2 * item 12 depth -= 1 13 return (item, make_tree(item2 - 1, depth), make_tree(item2, depth)) 14 else: 15 return (item, None, None) 16 17 def check_tree((item, left, right)): 18 if left is not None: 19 return item + check_tree(left) - check_tree(right) 20 else: 21 return item 22 23 def main(): 24 min_depth = 4 25 max_depth = max(min_depth + 2, int(argv[1])) 26 stretch_depth = max_depth + 1 27 28 print "stretch tree of depth %d\t check: %d" % (stretch_depth, check_tree(make_tree(0, stretch_depth))) 29 30 long_lived_tree = make_tree(0, max_depth) 31 32 for depth in xrange(min_depth, stretch_depth, 2): 33 iterations = 2**(max_depth - depth + min_depth) 34 35 check = 0 36 for i in xrange(1, iterations + 1): 37 check += check_tree(make_tree(i, depth)) + check_tree(make_tree(-i, depth)) 38 39 print "%d\t trees of depth %d\t check: %d" % (iterations * 2, depth, check) 40 41 print "long lived tree of depth %d\t check: %d" % (max_depth, check_tree(long_lived_tree)) 42 43 if __name__ == '__main__': 44 main()