Skip to content

Commit

Permalink
+ SphereCollatz.py. Resolves #5
Browse files Browse the repository at this point in the history
  • Loading branch information
Mark committed Jun 15, 2014
1 parent c631fab commit 057c2f5
Showing 1 changed file with 100 additions and 0 deletions.
100 changes: 100 additions & 0 deletions SphereCollatz.py
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)

0 comments on commit 057c2f5

Please sign in to comment.