3

I've done:

def collatz(n):
    seq = n
    if n == 1:
        n = n
    while n > 1:
       if n % 2 == 0:
           n = n // 2
       else:
           n = 3 * n + 1
    print(seq)

The corrct output for calling this function, while n = 10:

collatz(10)
10
5
16
8
4
2
1

But the only number printed is n itself.

Frank
  • 339
  • 8
  • 18

2 Answers2

2

The issue is that you are only printing seq which was set to n at start of the function, after the while loop has executed. Hence you only get the value printed once.

You should print the value inside the while loop as well as at start (for the first 10 print). Example -

def collatz(n):
    print(n)
    while n > 1:
       if n % 2 == 0:
           n = n // 2
       else:
           n = 3 * n + 1
       print(n)

Demo -

>>> def collatz(n):
...     print(n)
...     while n > 1:
...        if n % 2 == 0:
...            n = n // 2
...        else:
...            n = 3 * n + 1
...        print(n)
...
>>> collatz(10)
10
5
16
8
4
2
1
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
1
  • You need to print once for every step within your loop. Your print statement is outside your while loop hence it only fires once.
  • Additionally, you want to print the value that is changing n not seq which never chances in this function.
  • On that note, you don't even need seq as you never use it!
  • The two lines if n == 1: n = n don't do anything. Even if n==1, setting n to itself doesn't change the value.
Hooked
  • 84,485
  • 43
  • 192
  • 261