Search code examples
pythoncountercollatz

Using a counter in a python function


I am trying to count the iterations in a function, but I can't get it right. What is wrong with the code?

Every time I call the function, the counter give me zero as a result. I want to add a pause between iteration an print the result one by one, but I couldn't fix it.

My code is below:

n = 41

def collatz(n):
   
    count = 0

    if n != 1 and n % 2 == 1 :
        
        n = n * 3 + 1
        print(n) 
        count += 1
        collatz(n)
        
    
    elif n != 1 and n % 2 == 0:
        
        n = n / 2 
        print(n)
        count += 1 
        collatz(n)
        
    
    else:
        print('done')
        print(count)
        return
        
    
collatz(n)


Solution

  • Its because in each recursion/function call, its again set to 0. You can pass it as an argument to the function to get past it.

    Something like this should help solve it.

    def collatz(n, count=0):
       
        if n != 1 and n % 2 == 1 :
            
            n = n * 3 + 1
            print(n) 
            count += 1
            collatz(n, count)
            
        
        elif n != 1 and n % 2 == 0:
            
            n = n / 2 
            print(n)
            count += 1 
            collatz(n, count)
            
        
        else:
            print('done')
            print(count)
            return
            
        
    collatz(n)