2019-07-13 07:04:43 +00:00
|
|
|
from typing import Tuple, List
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
def n31(a: int) -> Tuple[List[int], int]:
|
2019-07-13 07:04:43 +00:00
|
|
|
"""
|
|
|
|
Returns the Collatz sequence and its length of any postiver integer.
|
|
|
|
>>> n31(4)
|
|
|
|
([4, 2, 1], 3)
|
|
|
|
"""
|
2018-11-03 20:08:13 +00:00
|
|
|
|
2019-07-13 07:04:43 +00:00
|
|
|
if not isinstance(a, int):
|
2019-10-05 05:14:13 +00:00
|
|
|
raise TypeError("Must be int, not {0}".format(type(a).__name__))
|
|
|
|
if a < 1:
|
|
|
|
raise ValueError("Given integer must be greater than 1, not {0}".format(a))
|
|
|
|
|
2019-07-13 07:04:43 +00:00
|
|
|
path = [a]
|
|
|
|
while a != 1:
|
|
|
|
if a % 2 == 0:
|
|
|
|
a = a // 2
|
|
|
|
else:
|
2019-10-05 05:14:13 +00:00
|
|
|
a = 3 * a + 1
|
2019-07-13 07:04:43 +00:00
|
|
|
path += [a]
|
|
|
|
return path, len(path)
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2019-07-13 07:04:43 +00:00
|
|
|
def main():
|
|
|
|
num = 4
|
2019-10-05 05:14:13 +00:00
|
|
|
path, length = n31(num)
|
|
|
|
print(
|
|
|
|
"The Collatz sequence of {0} took {1} steps. \nPath: {2}".format(
|
|
|
|
num, length, path
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
2018-11-03 20:08:13 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
2018-10-28 21:36:39 +00:00
|
|
|
main()
|