HeiHei
HeiHei

Reputation: 3

Find the length of a Collatz conjecture sequence

I am trying to find the length of a Collatz conjecture sequence but my answer is wrong.... What's wrong with my code? I could not find relevant solution on the internet...

a=int(input())
mylist=[]
while a != 1:
    if a%2 == 0:
        a = a/2
    else:
        a = a*3 + 1
        mylist.append(a)
print(len(mylist))

Input:6

Output:2

If I input 6, the answer should be 9. I am trying to put them into a list and then find the length of the list.

Upvotes: 0

Views: 1532

Answers (1)

decorator-factory
decorator-factory

Reputation: 3083

The indentation is off:

a=int(input())
6
mylist=[]
while a != 1:
    if a%2 == 0:
        a = a/2
    else:
        a = a*3 + 1
    mylist.append(a) # HERE
print(len(mylist))

Python distinguishes code blocks using indentation. Because of the wrong indentation, mylist.append(a) would only run in the else branch and would not add any of the even numbers. You could print mylist and notice that.

Also, it would probably be better to use // (integer division) instead of / (float division) to keep a integer.

Upvotes: 2

Related Questions