r""" Python module for OEIS sequence number A004001. Hofstadter-Conway $10000 sequence: a(1) = a(2) = 1; for n > 2, a(n) = a(a(n-1)) + a(n-a(n-1)). Examples of use. ----------------------------------------------------------------------- >>> from a004001 import * >>> print a004001_list(18) [1, 1, 2, 2, 3, 4, 4, 4, 5, 6, 7, 7, 8, 8, 8, 8, 9, 10] >>> print a004001_offset 1 >>> for x in a004001_list_pairs(6): ... print x ... (1, 1) (2, 1) (3, 2) (4, 2) (5, 3) (6, 4) >>> print a004001(100) 57 ----------------------------------------------------------------------- """ from itertools import islice, izip, count __all__ = ('a004001_offset', 'a004001_list', 'a004001_list_pairs', 'a004001', 'a004001_gen') __author__ = 'Nick Hobson ' a004001_offset = offset = 1 def a004001_gen(): """Generator function for OEIS sequence A004001.""" a = {1:1, 2:1} yield a[1] yield a[2] for n in count(3): a[n] = a[a[n-1]] + a[n-a[n-1]] yield a[n] def a004001_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(a004001_gen(), n)) def a004001_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(a004001_offset, n+a004001_offset), a004001_gen())) def a004001(n): """Returns the term with index n >= 1; offset 1.""" if n < offset: raise ValueError, 'Input must be an integer >= offset = ' + str(offset) return list(islice(a004001_gen(), n-a004001_offset, n-a004001_offset+1)).pop()