Anvit
Anvit

Reputation: 228

Resetting Collatz Counter on Each New Recursion

I made a code that measure number of steps it takes to return to 1 in a Collatz Conjecture. Here Is my code

counter = 0
def collatz(n):
    global counter 
    counter += 1
    if n <= 0 :
        return "Invalid Number"
    elif n == 1 :
        return counter
    elif n % 2 == 1 :
        n = 3*n + 1
        return collatz(n)
    elif n % 2 == 0 :
        n = n/2
        return collatz(n)   
print(collatz(9921615699))
print(collatz(9921615699))

I expect the Last two print commands to print 311 and 311. Instead, they print 311 and 622. I guess that was easy enough to see in the code what is wrong. How can i fix that? how can counter reset each time a command is completed and not when the function is run.

Upvotes: 1

Views: 109

Answers (2)

Wayne Werner
Wayne Werner

Reputation: 51847

You're using recursion, so just use it properly:

def collatz(n, counter=0):
    counter += 1
    if n <= 0 :
        return "Invalid Number"
    elif n == 1 :
        return counter
    elif n % 2 == 1 :
        n = 3*n + 1
        return collatz(n, counter)
    elif n % 2 == 0 :
        n = n/2
        return collatz(n, counter)   
print(collatz(9921615699))
print(collatz(9921615699))

You were using global in your original version which is usually not what you want to do. You got to see first-hand why.

You could have reset the counter, e.g.

result = counter
counter = 0
return result

But that's pretty nasty, let's not do that. When you're implementing a recursive algorithm there's probably no good reason to have a global variable.

Upvotes: 1

niemmi
niemmi

Reputation: 17263

Instead of using global variable you could make the counter a parameter with default value:

def collatz(n, counter=0):
    counter += 1
    if n <= 0 :
        return "Invalid Number"
    elif n == 1 :
        return counter
    elif n % 2 == 1 :
        n = 3*n + 1
        return collatz(n, counter)
    elif n % 2 == 0 :
        n = n/2
        return collatz(n, counter)

Upvotes: 4

Related Questions