r""" Python module for OEIS sequence number A005374. a(0) = 0; for n > 0, a(n) = n - a(a(a(n-1))). Examples of use. ----------------------------------------------------------------------- >>> from a005374 import * >>> print a005374_list(18) [0, 1, 1, 2, 3, 4, 4, 5, 5, 6, 7, 7, 8, 9, 10, 10, 11, 12] >>> print a005374_offset 0 >>> for x in a005374_list_pairs(6): ... print x ... (0, 0) (1, 1) (2, 1) (3, 2) (4, 3) (5, 4) >>> a005374_list_upto(9) [0, 1, 1, 2, 3, 4, 4, 5, 5, 6, 7, 7, 8, 9] >>> print a005374(200) 136 >>> a005374_list_inv(136) [199, 200] ----------------------------------------------------------------------- """ from itertools import islice, izip, takewhile, count __all__ = ('a005374_offset', 'a005374_list', 'a005374_list_pairs', 'a005374_list_upto', 'a005374', 'a005374_gen', 'a005374_list_inv') __author__ = 'Nick Hobson <nickh@qbyte.org>' a005374_offset = offset = 0 def a005374_gen(): """Generator function for OEIS sequence A005374.""" a = {0:0} yield a[0] for n in count(1): a[n] = n - a[a[a[n-1]]] yield a[n] def a005374_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(a005374_gen(), n)) def a005374_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), a005374_gen())) def a005374_list_upto(m): """Returns a list of all terms not exceeding m >= 0.""" if m < 0: raise ValueError, 'Input must be a non-negative integer' return list(takewhile(lambda t: t <= m, a005374_gen())) def a005374(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(a005374_gen(), n-offset, n-offset+1)).pop() def a005374_list_inv(m): """Returns a list of all indices n for which a(n) = m >= 0.""" if m < 0: raise ValueError, 'Input must be a non-negative integer' r, n = [], 0 for x in a005374_gen(): if x > m: break if x == m: r.append(n) n += 1 return r