fork download
  1. #!/usr/bin/env python3
  2.  
  3. def unfoldTree(f, b):
  4. match f(b):
  5. case a, bs:
  6. return [a, [unfoldTree(f, b) for b in bs]]
  7.  
  8. def foldTree(f, tree):
  9. def go(node):
  10. match node:
  11. case x, ts:
  12. return f(x, [go(child) for child in ts])
  13. return go(tree)
  14.  
  15. if __name__ == '__main__':
  16.  
  17. def buildNode(x):
  18. return (x, []) if 2 * x + 1 > 7 else (x, [2*x, 2*x + 1])
  19.  
  20. # 二分木の生成
  21. print(unfoldTree(buildNode, 1))
  22. # 木の値の総和
  23. print(foldTree(lambda x, xs: sum([x] + xs), [1, [[2, []], [3, []]]]))
  24. # 木の値の最大値
  25. print(foldTree(lambda x, xs: max([x] + xs), [1, [[2, []], [3, []]]]))
  26. # 木の葉の個数
  27. print(foldTree(lambda x, xs: 1 if xs == [] else sum(xs), [1, [[2, []], [3, []]]]))
  28. # 木の高さ
  29. print(foldTree(lambda x, xs: 0 if xs == [] else 1 + max(xs), [1, [[2, []], [3, []]]]))
  30.  
  31. # フィボナッチ数列
  32. def fib(n):
  33. def g(n):
  34. match n:
  35. case 0:
  36. return (0, [])
  37. case 1:
  38. return (1, [])
  39. case n:
  40. return (n, [n - 1, n - 2])
  41. return foldTree(lambda x, xs: x if xs == [] else sum(xs), unfoldTree(g, n))
  42.  
  43. print(fib(5))
  44.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
Traceback (most recent call last):
  File "/usr/lib/python3.9/py_compile.py", line 144, in compile
    code = loader.source_to_code(source_bytes, dfile or file,
  File "<frozen importlib._bootstrap_external>", line 918, in source_to_code
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "./prog.py", line 4
    match f(b):
          ^
SyntaxError: invalid syntax

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.9/py_compile.py", line 150, in compile
    raise py_exc
py_compile.PyCompileError:   File "./prog.py", line 4
    match f(b):
          ^
SyntaxError: invalid syntax

stdout
Standard output is empty