Collatz conjecture sequence

You forgot to append the x values to the seq list:

def collatz_sequence(x):
    seq = [x]
    if x < 1:
       return []
    while x > 1:
       if x % 2 == 0:
         x = x / 2
       else:
         x = 3 * x + 1 
       seq.append(x)    # Added line
    return seq

Verification:

~/tmp$ python collatz.py 
[6, 3, 10, 5, 16, 8, 4, 2, 1]

def collatz_sequence(x):
    seq = [x]
    while seq[-1] > 1:
       if x % 2 == 0:
         seq.append(x/2)
       else:
         seq.append(3*x+1)
       x = seq[-1]
    return seq

Here's some code that produces what you're looking for. The check for 1 is built into while statement, and it iteratively appends to the list seq.

>>> collatz_sequence(6)
[6, 3, 10, 5, 16, 8, 4, 2, 1]

Note, this is going to be very slow for large lists of numbers. A cache won't solve the speed issue, and you won't be able to use this in a brute-force solution of the project euler problem, it will take forever (as it does every calculation, every single iteration.)

Tags:

Python