Skip to content Skip to sidebar Skip to footer

Collatz Sequence. (python 3)

I've started the book 'Automate The Boring Stuff' by Al Sweigart. At the end of Chapter 3, the author suggests creating a Collatz Sequence in Python as a practice exercise. (the p

Solution 1:

return exits the function and, therefore terminates your while loop.

Perhaps you meant to use yield instead:

print("This is The Collatz Sequence")
user = int(input("Enter a number: "))

defcollatz(n):
    print(n)
    while n != 1:
        if n % 2 == 0:
            n = n // 2yield(n)
        else:
            n = n * 3 + 1yield(n)

print(list(collatz(user)))

Output:

This is The Collatz Sequence
Enter a number: 33
[10, 5, 16, 8, 4, 2, 1]

Yield is logically similar to a return but the function is not terminated until a defined return or the end of the function is reached. When the yield statement is executed, the generator function is suspended and the value of the yield expression is returned to the caller. Once the caller finishes (and assumably uses the value that was sent) execution returns to the generator function right after the yield statement.

Solution 2:

In your code you don't re-feed the new value back into your equation. Try separating your while loop from the collatz module. I have an example of this below:

defcollatz(number):
    if number % 2 == 0:
        return number // 2elif number % 2 == 1:
        return3 * number + 1

chosenInt = int(input('Enter an integer greater than 1: '))

print(chosenInt)

while chosenInt != 1:
    chosenInt = collatz(chosenInt)
    print(chosenInt)

Solution 3:

defcollatz(number):
if (number%2 == 0):
    returnprint(number//2);
else:
    return (print(number*3+1));

inputNumber = input("Enter a number greater than 1:");
result = collatz(int(inputNumber));
while result != 1:
    result = collatz(result);

I am getting a typeError with it! Don't know why?

Post a Comment for "Collatz Sequence. (python 3)"