#Collatz Conjecture | Python

12 messages · Page 1 of 1 (latest)

graceful ridge
#

I wrote the code, but in the end it tells me that the solution is too long

def steps(number):

    stop = True
    count = 0

    if number <1:
        raise ValueError("Only positive integers are allowed")

    while stop:
        if number == 1:
            stop = False
        if number % 2 == 0:
            number = number / 2
            count + 1
        if number % 2 != 0:
            number = number * 3 + 1
            count + 1      
    return count ```
#

Collatz Conjecture | Python

brazen barn
brazen barn
#

So what's the error? The code just takes to long?

graceful ridge
#

Your tests timed out
Your tests timed out. This might mean that there was an issue in our infrastructure, but more likely it suggests that your code is running slowly. Is there an infinite loop or something similar?

Please check your code, and if nothing seems to be wrong, try running the tests again.

brazen barn
#

Ok this could simply mean that the website is actually slow rn

But to speed up your code make the last if simply an else
And the second to last an elif.

That way we prevent from having to check all 3 conditions inside the while loop everytime

graceful ridge
#

thank you, I did this

while stop:
        if number % 2 == 0:
            number = number / 2
            count =+ 1
        elif number == 1:
            stop = False
        else:
            number = number * 3 + 1
            count =+ 1      
    return count

but it works strangely, for example: when entering 12 it should be 9, but it outputs 1

brazen barn
#

You have to do += not =+

#

count += 1 reads as: "Take the value of count and add the value 1 to it"

count =+ 1 reads as: "The value of count should be positive 1"

graceful ridge
#

Thanks, I did it and everything worked ❤️

brazen barn
#

All Tests pass?