fork download
  1. from typing import Callable, Iterator
  2.  
  3. def unfold[T](k: T, f: Callable[[T], T]) -> Iterator[T]:
  4. """
  5. Unfold a sequence from an initial value.
  6.  
  7. Unfold creates a (potentially infinite) sequence by continuously
  8. applying f to k, and storing the result back in k.
  9.  
  10. Iteration is interrupted when f raises StopIteration.
  11.  
  12. The initial k is always present in the resulting sequence.
  13. """
  14. yield k
  15. while True:
  16. try:
  17. k = f(k)
  18. except StopIteration:
  19. break
  20. else:
  21. yield k
  22.  
  23. def next_collatz(n):
  24. if n <= 1:
  25. raise StopIteration()
  26. elif n % 2 == 0:
  27. return n // 2
  28. else:
  29. return n * 3 + 1
  30.  
  31. initial = int(input())
  32. unfold_collatz = unfold(initial, next_collatz)
  33. print(list(unfold_collatz))
Success #stdin #stdout 0.16s 16636KB
stdin
119
stdout
[119, 358, 179, 538, 269, 808, 404, 202, 101, 304, 152, 76, 38, 19, 58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]