fork download
  1. #!/usr/bin/env python3
  2.  
  3. from functools import reduce
  4.  
  5. ### 余再帰
  6. class unfoldr:
  7. def __init__(self, f, seed):
  8. self.f = f
  9. self.seed = seed
  10. def __iter__(self):
  11. return self
  12. def __next__(self):
  13. match self.f(self.seed):
  14. case a, b:
  15. self.seed = b
  16. return a
  17. case None:
  18. raise StopIteration
  19. def __reversed__(self):
  20. return reversed(list(self))
  21.  
  22. def codeInfo(n):
  23. lst = [0] + list(unfoldr(lambda x: None if x == n else (sum([2 ** i for i in range(1, 1 + x)]), 1 + x), 1))
  24. return [*lst, 1 + lst[-1]]
  25.  
  26. # 各要素の発生回数を数える
  27. def countDatum(data):
  28. def foo(d, elt):
  29. try:
  30. d[elt] += 1
  31. except KeyError:
  32. d[elt] = 1
  33. finally:
  34. return d
  35. # 今回は最大値から降順でソートする
  36. return sorted([[v, k]for k, v in reduce(foo, list(data), {}).items()], reverse = True)
  37.  
  38. def compress(data):
  39. lst0 = lambda: countDatum(data) # 再利用の為サンクを作る
  40. lst1 = codeInfo(len(lst0()) - 1)
  41. lst2 = lambda: zip([i[1] for i in lst0()], lst1) # 再利用の為サンクを作る
  42. d = dict(lst2())
  43. return [d[key] for key in data], {k: v for v, k in lst2()}
  44.  
  45. if __name__ == '__main__':
  46. # Wikipediaと、DとEにアテられる数値が違うが、そもそもDとEの出現率は同じだ。
  47. # ソートによっては「安定ソート」な為、元の順番を保持しようとする。
  48. # しかし、結果、こちらのエンコード/デコードでも「理論上は」問題がない。
  49. print(compress("DAEBCBACBBBC"))
  50.  
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 13
    match self.f(self.seed):
          ^
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 13
    match self.f(self.seed):
          ^
SyntaxError: invalid syntax

stdout
Standard output is empty