binary-trees MicroPython #8 program
source code
# The Computer Language Benchmarks Game
# https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
#
# contributed by Isaac Gouy
import sys
class Tree:
def __init__(self, left, right):
self.left = left
self.right = right
def with_(depth):
return Tree(None, None) if (depth == 0) \
else Tree( Tree.with_(depth-1), Tree.with_(depth-1) )
def node_count(self):
return 1 if (self.left == None) \
else 1 + self.left.node_count() + self.right.node_count()
def main(n):
MIN_DEPTH = 4
max_depth = (MIN_DEPTH + 2) if (MIN_DEPTH + 2 > n) else n
stretch_depth = max_depth + 1
count = (Tree.with_(stretch_depth)).node_count()
print("stretch tree of depth %d\t check:" % stretch_depth, count)
long_lived_tree = Tree.with_(max_depth)
for depth in range(MIN_DEPTH, stretch_depth, 2):
iterations = 1 << (max_depth - depth + MIN_DEPTH)
count = 0
for i in range(iterations):
count += (Tree.with_(depth)).node_count()
print("%d\t trees of depth %d\t check:" %
(iterations, depth), count)
print("long lived tree of depth %d\t check:" %
max_depth, long_lived_tree.node_count())
if __name__ == '__main__':
main( int(sys.argv[1]) )
notes, command-line, and program output
NOTES:
64-bit Ubuntu quad core
MicroPython v1.24.0
preview.44.ge9c898cb3
Tue, 08 Oct 2024 18:43:28 GMT
COMMAND LINE:
/opt/src/micropython/micropython -X heapsize=1024M -X emit=native binarytrees.micropython-8.micropython 21
PROGRAM OUTPUT:
stretch tree of depth 22 check: 8388607
2097152 trees of depth 4 check: 65011712
524288 trees of depth 6 check: 66584576
131072 trees of depth 8 check: 66977792
32768 trees of depth 10 check: 67076096
8192 trees of depth 12 check: 67100672
2048 trees of depth 14 check: 67106816
512 trees of depth 16 check: 67108352
128 trees of depth 18 check: 67108736
32 trees of depth 20 check: 67108832
long lived tree of depth 21 check: 4194303