Question

I am trying to make a program that calculates when a number will reach zero using the Collatz sequence. Here is my code for that program:

import time

def run(z):
    while z != 1:
        if isEven(z) == True:
            z = z/2
            print z
        else:
            z = (3*z)+1
            print z
    else:
        print 'Got one!'
        z = z+1
        print 'Trying for %d...' %(z)
        time.sleep(0.1)
        run(z)



def isEven(number):
        return number % 2 == 0

run(z)

However, the z never goes above 2, it only keeps printing:

Got one!
Trying for 2...
1
Got one!
Trying for 2...
1

And so on... Can anyone tell me what I am doing wrong?

Was it helpful?

Solution

The Collatz conjecture is that you will reach one, not zero; when you reach one, you should stop. Also, you have an odd combination of while loop and recursive calling. A very simple recursive implementation:

def collatz(n):
    print(n)
    if n == 1: # base case
        print("Done!")
    else:
        if n % 2: # odd number
            collatz((3 * n) + 1)
        else: # even number
            collatz(n / 2)

or iterative version:

def collatz(n):
    while n != 1:
        print(n)
        if n % 2: # odd number
            n = (3 * n) + 1
        else: # even number
            n /= 2
    print(n)
    print("Done!")

If you want to analyse how long a number takes to reach one, you can rejig one of those implementations, e.g.:

def collatz(n):
    count = 0
    while n != 1:
        count += 1
        if n % 2: # odd number
            n = (3 * n) + 1
        else: # even number
            n /= 2
    return count

You can then call this function, working through the integers, creating the Collatz sequence for each one, for example:

seq_len = [(n, collatz(n)) for n in range(1, 101)]

OTHER TIPS

Once z is 1, you exit the while loop, entering the else, which calls run(2), which sets z back to 1, which calls run(2) and so on and so on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top