-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCollatz.py
executable file
·87 lines (76 loc) · 1.74 KB
/
Collatz.py
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
87
#!/usr/bin/env python3
# ---------------------------
# projects/collatz/Collatz.py
# Copyright (C) 2015
# Glenn P. Downing
# ---------------------------
cache = {}
# ------------
# collatz_read
# ------------
def collatz_read (s) :
"""
read two ints
s a string
return a list of two ints, representing the beginning and end of a range, [i, j]
"""
a = s.split()
return [int(a[0]), int(a[1])]
# ------------
# collatz_eval
# ------------
def collatz_eval (i, j) :
"""
i the beginning of the range, inclusive
j the end of the range, inclusive
return the max cycle length of the range [i, j]
"""
# <your code>
assert i > 0
assert j > 0
if i > j :
temp = i
i = j
j = temp
maxCycle = 0
for num in range(i, j + 1) :
n = num
if num in cache :
c = cache[num]
else :
c = 1
while n > 1 :
if (n % 2) == 0 :
n = (n // 2)
else :
n = (3 * n) + 1
c += 1
assert c > 0
cache[num] = c
maxCycle = max(maxCycle, c)
assert maxCycle > 0
return maxCycle
# -------------
# collatz_print
# -------------
def collatz_print (w, i, j, v) :
"""
print three ints
w a writer
i the beginning of the range, inclusive
j the end of the range, inclusive
v the max cycle length
"""
w.write(str(i) + " " + str(j) + " " + str(v) + "\n")
# -------------
# collatz_solve
# -------------
def collatz_solve (r, w) :
"""
r a reader
w a writer
"""
for s in r :
i, j = collatz_read(s)
v = collatz_eval(i, j)
collatz_print(w, i, j, v)