r"""
Python module for OEIS sequence number A128333.

a(0) = 0; for n > 0, a(n) = a(n-1)/2 if that number is an integer and
not already in the sequence, otherwise a(n) = 3*a(n-1) + 1.

Examples of use.
-----------------------------------------------------------------------
>>> from a128333 import *
>>> print a128333_list(16)
[0, 1, 4, 2, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5]
>>> print a128333_offset
0
>>> for x in a128333_list_pairs(6):
...     print x
...
(0, 0)
(1, 1)
(2, 4)
(3, 2)
(4, 7)
(5, 22)
>>> print a128333(3)
2
-----------------------------------------------------------------------
"""

from itertools import islice, izip, count

__all__ = ('a128333_offset', 'a128333_list', 'a128333_list_pairs', 'a128333', 'a128333_gen')
__author__ = 'Nick Hobson <nickh@qbyte.org>'

a128333_offset = offset = 0

def a128333_gen():
    """Generator function for OEIS sequence A128333."""
    s, x = set(), 0
    while True:
        yield x
        s.add(x)
        x = x/2 if x%2 == 0 and x/2 not in s else 3*x + 1

def a128333_list(n):
    """Returns a list of the first n >= 0 terms."""
    if n < 0: raise ValueError, 'Input must be a non-negative integer'
    return list(islice(a128333_gen(), n))

def a128333_list_pairs(n):
    """Returns a list of tuples (n, a(n)) of the first n >= 0 terms."""
    if n < 0: raise ValueError, 'Input must be a non-negative integer'
    return list(izip(xrange(offset, n+offset), a128333_gen()))

def a128333(n):
    """Returns the term with index n >= 0; offset 0."""
    if n < offset: raise ValueError, 'Input must be an integer >= offset = ' + str(offset)
    return list(islice(a128333_gen(), n-offset, n-offset+1)).pop()