-1

experts.

I'm trying to define a function (collatz) that:

  1. Asks for a number. If it is even it prints number // 2, if it odd it prints 3 * number + 1. (OK)
  2. The result, whatever it is, must enter a loop until the result is 1. (NOK)

So, i´m not figure out because the result is not used and is in an infinite loop. Any suggestion?

def collatz():
    number = int(input('Enter the number: '))
    x = number % 2
    while number != 1:
        if x == 0:
            print(f'{number // 2}')
        else:
            print(f'{3 * number + 1}')
        number = number

print(f'{collatz()}')
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 1
    Just do `number = number // 2` or `number = 3 * number + 1` and then just `print(number)` once. – ddejohn Feb 24 '21 at 02:03
  • You don't need to worry about that, the Collatz conjecture ensures that it will always converge to 1. You could try to add an exit condition but you won't be able to test that it works. Alternatively you could give it a maximum run time (let's say 30 second) and check that execution time is not exceeded at every loop. – Alain T. Feb 24 '21 at 02:31
  • You are not updating the value of number, it is remaining same in the loop – Mohil Patel Feb 24 '21 at 02:46

1 Answers1

1

You need to actually assign the result back to number.

As well:

  • The divisibility check needs to be in the loop.
  • The outer print() is not needed.
  • The f-strings are redundant. print() converts its arguments to string automatically.
def collatz():
    number = int(input('Enter the number: '))
    while number != 1:
        if number % 2 == 0:
            number //= 2  # Short for "number = number // 2"
        else:
            number = 3*number + 1
        print(number)

collatz()

Example run:

Enter the number: 3
10
5
16
8
4
2
1
wjandrea
  • 28,235
  • 9
  • 60
  • 81