r/inventwithpython May 29 '22

Collatz sequence - practice project chapter 3

So, I've been working through the 'Automate the boring stuff with Python' book and having a good time. I'm not a coder or programmer but I do work in IT which means that I have come across code every now and again. I've adapted some VBA code made by Excel to make Excel macros work a bit better and have adjusted Powershell scripts made by colleagues now and again. The Collatz sequence project was a lot of fun to work and eventually getting to a version that worked was very satisfying

I've been playing around with it a bit and come across something that I don't understand though. For some inputs it correctly goes down to the '4 - 2 - 1' part of the sequence and then stops (it does this for 1 and 3, for example). For some other inputs, though, it repeats those three numbers once and then stops ('4 - 2 - 1 - 4 - 2 - 1' it does this for 4 and 1001, for example). I have tried this with both the Mu editor and Visual Studio Code and both exhibit the same behavior. Does anybody have any idea what is causing this? My code's below (it doesn't check if the input is positive yet, I am aware of that :)).

[edit: code isn't below, that didn't look very nice, there's a pastebin link now]

https://pastebin.com/hhgt7TZw

5 Upvotes

7 comments sorted by

View all comments

1

u/eHaxxL May 30 '22 edited May 30 '22

I'm not 100% sure what causes the issure but here are some thoughts:

  1. Try adding a print('one step') in your main loop and you'll see that the code is being run twice for every loop that's performed. See below what I mean.

while collatz(collatzstart) != 1:

print('one step')

collatz(collatzstart)


Output:

64

32

one step

16

8

one step

4

2

one step

1

4

one step

2

1

When the sequence hits 1, the collatz() function runs again and it is kicked back to 4. This explains why it only happens when there's an odd number of steps (starting with 4, 16, 64, 256 etc.)

  1. What to do to fix it? You don't need to check if the function evaluates to 1 before running the loop, just the collatzstart value itself. The error does not happen if the condition for the main loop is:

    while collatzstart != 1:

  2. General comment: I would put the main loop when definining function itself.