1

I was just writing a little python program to run the Collatz algorithm and I think the while loop isn't breaking when it should. I'm running this whith VSCode 1.44.2 and Python 3.7.5 64bit

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

collatz(3)

and here is the complete output

10
5.0
16.0
8.0
4.0
2.0
1.0
1.0
2.0
1.0
1.0
4.0
2.0
1.0
1.0
2.0
1.0
1.0
8.0
4.0
2.0
1.0
1.0
2.0
1.0
1.0
4.0
2.0
1.0
1.0
2.0
1.0
1.0
16.0
8.0
4.0
2.0
1.0
1.0
2.0
1.0
1.0
4.0
2.0
1.0
1.0
2.0
1.0
1.0
8.0
4.0
2.0
1.0
1.0
2.0
1.0
1.0
4.0
2.0
1.0
1.0
2.0
1.0
1.0
5.0
16.0
8.0
4.0
2.0
1.0
1.0
2.0
1.0
1.0
4.0
2.0
1.0
1.0
2.0
1.0
1.0
8.0
4.0
2.0
1.0
1.0
2.0
1.0
1.0
4.0
2.0
1.0
1.0
2.0
1.0
1.0
16.0
8.0
4.0
2.0
1.0
1.0
2.0
1.0
1.0
4.0
2.0
1.0
1.0
2.0
1.0
1.0
8.0
4.0
2.0
1.0
1.0
2.0
1.0
1.0
4.0
2.0
1.0
1.0
2.0
1.0
1.0

The program ended at this point without an error. When I step through the program I see a message "(return) collatz: None" when n=1.0 and the next debugger step goes to the beginning of the while loop again. Why isn't the program ending at this point? Since it's not ending when n=1, why does it end eventually and doesn't run forever?

rioV8
  • 24,506
  • 3
  • 32
  • 49
sevi
  • 460
  • 5
  • 20
  • 3
    fix indentation. Seems like you're mixing loop and recursion when you need only one of them. – Vicrobot Apr 28 '20 at 15:24
  • yes you're right :) removing the function call within the while loop gives me the correct result. thanks a lot! – sevi Apr 28 '20 at 15:27

1 Answers1

2

Your loop only appears to repeat after n reaches 1 because your function calls itself recursively, on the line I've marked below:

def collatz(n):
    while n != 1.0:
        if n%2 == 0:
            n = n/2
        else:
            n = 3*n+1
        print(n)
        # recursive call here
        collatz(n)

Because your function calls itself recursively, then when n reaches 1 the while loop does terminate but that only means the current recursive call returns and then the one below it on the stack resumes, doing more printing.

To fix your problem, you should use just a while loop or just recursion, not both.

kaya3
  • 47,440
  • 4
  • 68
  • 97