-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExercise39.py
More file actions
58 lines (38 loc) · 1.24 KB
/
Copy pathExercise39.py
File metadata and controls
58 lines (38 loc) · 1.24 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
def collatz(startingNumber: int) -> list:
"""
List the numeric sequence.
Begin with a positive, nonzero integer called n.
If n is 1, the sequence terminates.
If n is even, the next value of n is n / 2.
If n is odd, the next value of n is 3n + 1.
:param startingNumber: startingNumber in int
:type startingNumber: int
:raise TypeError: If startingNumber is not a int
:return: list
:rtype: list
"""
if startingNumber < 1:
return []
sequence = [startingNumber]
num = startingNumber
while num > 1:
if num % 2 == 0:
num = num // 2
else:
num = 3 * num + 1
sequence.append(num)
return sequence
...
assert collatz(0) == []
assert collatz(10) == [10, 5, 16, 8, 4, 2, 1]
assert collatz(11) == [11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
assert collatz(12) == [12, 6, 3, 10, 5, 16, 8, 4, 2, 1]
assert len(collatz(256)) == 9
assert len(collatz(257)) == 123
import random
random.seed(42)
for i in range(1000):
startingNum = random.randint(1, 10000)
seq = collatz(startingNum)
assert seq[0] == startingNum # Make sure it includes the starting number.
assert seq[-1] == 1 # Make sure the last integer is 1.