Collatz Conjecture in Python

Please read the wikipedia Collatz Conjecture first. Here the python function for the injecture:

def collatz(n):
    return n / 2 if n % 2 == 0 else  3 * n + 1

When you sequence , you get the result:

n = 10
sequence = [n]
while n != 1:
    n = collatz(n)
    sequence.append(n)

Generator functions are lazy. Using yield statement you can create generator function as follows:

def collatz_iter(n):
    while n != 1:
        n = collatz(n)
        yield n

Above function is lazy. It doesn’t compute, until iterate over that:

s =collatz_iter(10)
for i in s:
    print(i)

Reference:

The Five Kinds of Python Functions by Steven F. Lott Publisher: O’Reilly Media, Inc.

Comments

Popular posts from this blog

How To: GitHub projects in Spring Tool Suite

Spring 3 Part 7: Spring with Databases

Parse the namespace based XML using Python