fork download
  1. #!/usr/bin/env python3
  2.  
  3. from math import sqrt
  4.  
  5. class primes(object):
  6. def __init__(self, n):
  7. # 構造体と違うのは、与えられたデータが一つでも、「計算に使うデータ」を
  8. # 内部的に設定しておける、と言う辺りだ。
  9. self.n = n
  10. self.lst = list(range(2, n + 1))
  11. def __iter__(self):
  12. return self
  13. def __next__(self):
  14. if self.lst == []:
  15. raise StopIteration
  16. else:
  17. match self.lst:
  18. case [head, *tail]:
  19. self.lst = tail if head > sqrt(self.n) \
  20. else [i for i in self.lst if i % head != 0]
  21. return head
  22.  
  23. class prime_factors(object):
  24. def __init__(self, n):
  25. self.n = n
  26. self.N = n
  27. self.primes = list(primes(n))
  28. def __iter__(self):
  29. return self
  30. def __next__(self):
  31. while True:
  32. match self.primes:
  33. case [head, *tail]:
  34. if head > sqrt(self.N):
  35. raise StopIteration
  36. elif self.n % head == 0:
  37. self.n //= head
  38. return head
  39. else:
  40. self.primes = tail
  41.  
  42. if __name__ == '__main__':
  43. print(list(primes(120))) # 120以下の素数
  44. print(list(prime_factors(48))) # 48 を素因数分解
  45. print(list(prime_factors(20100))) # 20100 を素因数分解
  46.  
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 17
    match self.lst:
          ^
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 17
    match self.lst:
          ^
SyntaxError: invalid syntax

stdout
Standard output is empty