-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathcollatz.py
More file actions
86 lines (51 loc) · 1.53 KB
/
collatz.py
File metadata and controls
86 lines (51 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env python3
#My comment to show a change for the homework
'''
Collatz code for CS 401
Author: Andrew Solis
'''
from typing import List
def compute_collatz( num : int ) -> List[int]:
'''
Calculates the sequence for the collatz conjecture given number 'num'.
Return the list of sequence.
Args:
num (int): initial number for starting collatz computation.
Returns:
result( List[int] ): Collatz sequence.
'''
result = []
result.append( num )
while num != 1:
if num % 2 == 0:
num = num // 2
result.append( num )
else:
num = 3 * num + 1
result.append( num )
return result
def print_collatz( collatz_list : List[int] ):
'''
Print out list for collatz conjecture of number.
Args:
collatz_list( List[int] ): collatz conjecture for number in list form.
'''
print( collatz_list[0], end="")
# print( collatz_list)
for i in range( 1, len(collatz_list ) ):
print( f' -> { collatz_list[i] }', end="" )
# put ending of line
print()
def main():
print('Collatz')
print('=======\n')
with open('input.txt') as file:
lines = [line.rstrip() for line in file]
for line in lines:
print( line )
num = int( line )
num_collatz = compute_collatz( num )
print_collatz( num_collatz )
print(f'num sequences: {len(num_collatz) - 1}\n' )
if __name__ == '__main__':
main()