HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Generator for the collatz conjecture sequence

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thegeneratorconjecturesequenceforcollatz

Problem

I tried to write this code as concisely as possible. Is this the best way to do it?

def collatz(n):
    """
    Generator for collatz sequence beginning with n

    >>> list(collatz(10))
    [5, 16, 8, 4, 2, 1]
    """
    while n != 1:
        n = n / 2 if n % 2 == 0 else 3*n + 1
        yield int(n)

Solution

The only improvement I see here is to divide n by 2 using // (since we are dealing with Python 3.x) and to remove the explicit conversion to int (int(n)):

while n != 1:
    n = n // 2 if n % 2 == 0 else 3*n + 1
    yield n


Also, I suggest you put a single space before and after the multiplication operator in 3n, so that it becomes 3 n.

Hope that helps.

Code Snippets

while n != 1:
    n = n // 2 if n % 2 == 0 else 3*n + 1
    yield n

Context

StackExchange Code Review Q#144801, answer score: 4

Revisions (0)

No revisions yet.