Collatz - assert v> 0 return v...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
#!/usr/bin/env python # ---------------------------------- # projects/python/collatz/Collatz.py # Copyright (C) 2010 # Glenn P. Downing # ---------------------------------- # ------------ # collatz_read # ------------ def collatz_read (r, a) : """ reads an int into a[0] and a[1] return true if that succeeds, false otherwise """ try : s = r.read() except EOFError : return False assert type(s) is str l = s.split() assert type(l) is list a[0:] = [int(l[0])] a[1:] = [int(l[1])] assert a[0] > 0 assert a[1] > 0 return True # ------------ # collatz_eval # ------------ def collatz_eval (a) : """ computes the max cycle length in the range [i, j] and stores the result in v """ assert len(a) == 2 for v in a: if v <= 0: return 0 v = max(map(cycle_length, range(min(a), max(a) + 1)))
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: assert v > 0 return v # ------------# cycle_length # ------------cycle_length_cache = {} cycle_length_cache[1] = 1 def cycle_length(n) : """ Returns the cycle length for n. Uses a memoizing cache for performance. """ assert type(n) in (int, long) assert n > 0 if n in cycle_length_cache : return cycle_length_cache[n] if (n % 2) == 1 : # length = cycle_length(3 * n + 1) + 1 length = cycle_length((n >> 1) + n + 1) + 2 else : length = cycle_length(n / 2) + 1 assert type(length) is int assert length > 0 cycle_length_cache[n] = length return length # -------------# collatz_print # -------------def collatz_print (w, a, v) : """ prints the values of a[0], a[1], and v """ w.write(a, v)...
View Full Document

{[ snackBarMessage ]}

Page1 / 2

Collatz - assert v> 0 return v...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online