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 clear(self):
if self.left != None:
self.left.clear()
del self.left
self.right.clear()
del self.right
def main(n):
MIN_DEPTH = 4
max_depth = (MIN_DEPTH + 2) if (MIN_DEPTH + 2 > n) else n
stretch_depth = max_depth + 1
stretch(stretch_depth)
long_lived_tree = Tree.with_(max_depth)
for depth in range(MIN_DEPTH, stretch_depth, 2):
iterations = 1 << (max_depth - depth + MIN_DEPTH)
sum = 0
for i in range(iterations):
sum += count(depth)
print("%d\t trees of depth %d\t check:" % (iterations, depth), sum)
c = long_lived_tree.node_count();
long_lived_tree.clear();
print("long lived tree of depth %d\t check:" % max_depth, c)
def stretch(depth):
print("stretch tree of depth %d\t check:" % depth, count(depth))
def count(depth):
t = Tree.with_(depth);
c = t.node_count();
t.clear();
return c;
if __name__ == '__main__':
main( int(sys.argv[1]) if len(sys.argv) > 1 else 10 )
notes, command-line, and program output
NOTES:
64-bit Ubuntu quad core
MicroPython v1.24.0
preview.44.ge9c898cb3
Tue, 29 Oct 2024 23:02:11 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