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

a(0) = 0; for n > 0, a(n) = n - a(a(a(a(n-1)))).

Examples of use.
-----------------------------------------------------------------------
>>> from a005375 import *
>>> print a005375_list(18)
[0, 1, 1, 2, 3, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10, 11, 11, 12]
>>> print a005375_offset
0
>>> for x in a005375_list_pairs(6):
...     print x
...
(0, 0)
(1, 1)
(2, 1)
(3, 2)
(4, 3)
(5, 4)
>>> print a005375(100)
73
-----------------------------------------------------------------------
"""

from itertools import islice, izip, count

__all__ = ('a005375_offset', 'a005375_list', 'a005375_list_pairs', 'a005375', 'a005375_gen')
__author__ = 'Nick Hobson <nickh@qbyte.org>'

a005375_offset = offset = 0

def a005375_gen():
    """Generator function for OEIS sequence A005375."""
    a = {0:0}
    yield a[0]
    for n in count(1):
        a[n] = n - a[a[a[a[n-1]]]]
        yield a[n]

def a005375_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(a005375_gen(), n))

def a005375_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), a005375_gen()))

def a005375(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(a005375_gen(), n-offset, n-offset+1)).pop()