|
| 1 | +[case testTree] |
| 2 | +from typing import Optional |
| 3 | +# This is bullshit |
| 4 | +class Node: |
| 5 | + def __init__(self) -> None: |
| 6 | + self.value = 0 |
| 7 | + self.left = None # type: Optional[Node] |
| 8 | + self.right = None # type: Optional[Node] |
| 9 | + def sum(self) -> int: |
| 10 | + left = 0 |
| 11 | + if self.left is not None: |
| 12 | + left = self.left.sum() |
| 13 | + right = 0 |
| 14 | + if self.right is not None: |
| 15 | + right = self.right.sum() |
| 16 | + return self.value + left + right |
| 17 | +def node(v: int) -> Node: |
| 18 | + x = Node() |
| 19 | + x.value = v |
| 20 | + x.left = None |
| 21 | + x.right = None |
| 22 | + return x |
| 23 | +def sum_tree(x: Optional[Node]) -> int: |
| 24 | + if x is None: |
| 25 | + return 0 |
| 26 | + return x.value + sum_tree(x.left) + sum_tree(x.right) |
| 27 | +def lol(n: int) -> Optional[Node]: |
| 28 | + if n == 0: |
| 29 | + return None |
| 30 | + x = node(n) |
| 31 | + x.left = lol(n - 1) |
| 32 | + x.right = x.left |
| 33 | + return x |
| 34 | +[file driver.py] |
| 35 | +from typing import Optional |
| 36 | +import native |
| 37 | +import interpreted |
| 38 | +from timeit import timeit |
| 39 | + |
| 40 | +def test(m): |
| 41 | + tree = m.lol(5) |
| 42 | + assert(m.sum_tree(tree) == 57) |
| 43 | + assert(tree.sum() == 57) |
| 44 | + |
| 45 | + g = {**globals(), **locals()} |
| 46 | + sum = timeit('m.sum_tree(tree)', globals=g) |
| 47 | + sum2 = timeit('tree.sum()', globals=g) |
| 48 | + build = timeit('m.lol(5)', globals=g) |
| 49 | + return (sum, sum2, build) |
| 50 | + |
| 51 | +nsum, nsum2, nbuild = test(native) |
| 52 | +isum, isum2, ibuild = test(interpreted) |
| 53 | +print("Sum speedup:", isum/nsum) |
| 54 | +print("Sum method speedup:", isum2/nsum2) |
| 55 | +print("Build speedup:", ibuild/nbuild) |
0 commit comments