title: Python - Memoization and Collatz Sequence
body: <p>When I was struggling to do <a href="http://projecteuler.net/problem=14" rel="noreferrer">Problem 14 in Project Euler</a>, I discovered that I could use a thing called memoization to speed up my process (I let it run for a good 15 minutes, and it still hadn't returned an answer). The thing is, how do I implement it? I've tried to, but I get a keyerror(the value being returned is invalid). This bugs me because I am positive I can apply memoization to this and get this faster.</p>
  
  <pre><code>lookup = {}
  
  def countTerms(n):
     arg = n
     count = 1
     while n is not 1:
        count += 1
        if not n%2:
           n /= 2
        else:
           n = (n*3 + 1)
        if n not in lookup:
           lookup[n] = count
  
     return lookup[n], arg
  
  print max(countTerms(i) for i in range(500001, 1000000, 2)) 
  </code></pre>
  
  <p>Thanks.</p>