Increasing speed of Project Euler #14 - Longest Collatz Sequence
You have a bug. Try calling collatz(2) a few times and you'll see the result increment by one each time.

The source of trouble is initializing count to 1. It means you always add at least 1 to the memoized value. Note however that initializing count to 0 instead would give incorrect results when the loop terminates by the n != 1 condition.

You can avoid this bug and simplify your code at the same time: if you initialize collatz_counts to {1: 1} you can loop while n not in collatz_counts: and eliminate the if ... break.


Note also that an odd number is always followed by an even number in the sequence, so you can take two steps with  n = (n * 3 + 1) // 2



I suppose you are on Python 3 because you are using print(). Note that n/=2 is float division. n becomes a float which slows down subsequent calculations. Use n //= 2 instead.