Hal Lawrence Hal Lawrence - 2 months ago 17
Python Question

Collatz sequence function?

What I am trying to do is count the steps when given a positive int x until it ends at 1. then if its an even number, divide in half to get the next int and if its odd, multiply it by 3 & add 1 to get the next int. But it will always break at 1. I'm getting an error on line 3 "TypeError: 'int' object is not iterable," and its been bothering me. Any advice/fixes appreciated.

Example test: collatz_counts(4) → 3 # 4 -> 2 -> 1 (3 steps)

Code I have:

def collatz_counts(x):
num = 0
for i in (x):
if i == 1:
num += 1
return num
elif i % 2 == 0:
num(i) / 2
num += 1
num.append(i)
else:
num = (i*2) + 3
num += 1
num.append(i)
return num

Answer

Use a while loop. Just modify x in place until you get to 1 and keep track of the number of steps each time you run a cycle.

def collatz_counts(x):
    steps = 0
    while x != 1:
        if x % 2:
            x = x * 3 + 1
        else:
            x = x // 2
        steps += 1
    return steps