-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Mark
committed
Jun 15, 2014
1 parent
c631fab
commit 057c2f5
Showing
1 changed file
with
100 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
#!/usr/bin/env python3 | ||
|
||
# ------------------------------ | ||
# Copyright (C) 2014 | ||
# Mark Sandan | ||
# ------------------------------ | ||
# ------- | ||
# imports | ||
# ------- | ||
|
||
import sys | ||
# ---- | ||
# main | ||
# ---- | ||
|
||
collatz_solve(sys.stdin, sys.stdout) | ||
|
||
# ------------ | ||
# collatz_read | ||
# ------------ | ||
|
||
def collatz_read (r) : | ||
""" | ||
read two ints | ||
r is a reader | ||
return a list of the two ints, otherwise a list of zeros | ||
""" | ||
s = r.readline() | ||
if s == "" : | ||
return [] | ||
a = s.split() | ||
return [int(v) for v in a] | ||
|
||
# ------------ | ||
# collatz_eval | ||
# ------------ | ||
|
||
def collatz_eval (i, j) : | ||
""" | ||
i is the beginning of the range, inclusive | ||
j is the end of the range, inclusive | ||
return the max cycle length in the range [i, j] | ||
""" | ||
# <your code> | ||
c_len=0 | ||
end=j+1 | ||
result=0 | ||
for num in range(i,end): | ||
result=cycle_length(num) | ||
if c_len < result: | ||
c_len=result | ||
|
||
return c_len | ||
|
||
# ------------- | ||
# cycle_length | ||
# ------------- | ||
def cycle_length (n) : | ||
assert n > 0 | ||
c = 1 | ||
while n > 1 : | ||
if (n % 2) == 0 : | ||
n = (n // 2) | ||
else : | ||
n = (3 * n) + 1 | ||
c += 1 | ||
assert c > 0 | ||
return c | ||
|
||
# ------------- | ||
# collatz_print | ||
# ------------- | ||
|
||
def collatz_print (w, i, j, v) : | ||
""" | ||
print three ints | ||
w is a writer | ||
i is the beginning of the range, inclusive | ||
j is the end of the range, inclusive | ||
v is the max cycle length | ||
""" | ||
w.write(str(i) + " " + str(j) + " " + str(v) + "\n") | ||
|
||
# ------------- | ||
# collatz_solve | ||
# ------------- | ||
|
||
def collatz_solve (r, w) : | ||
""" | ||
read, eval, print loop | ||
r is a reader | ||
w is a writer | ||
""" | ||
while True : | ||
a = collatz_read(r) | ||
if not a : | ||
return | ||
i, j = a | ||
v = collatz_eval(i, j) | ||
collatz_print(w, i, j, v) |