r""" Python module for OEIS sequence number A005185. Hofstadter Q-sequence: a(1) = a(2) = 1; for n > 2, a(n) = a(n-a(n-1)) + a(n-a(n-2)). Examples of use. ----------------------------------------------------------------------- >>> from a005185 import * >>> print a005185_list(18) [1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6, 8, 8, 8, 10, 9, 10, 11] >>> print a005185_offset 1 >>> for x in a005185_list_pairs(6): ... print x ... (1, 1) (2, 1) (3, 2) (4, 3) (5, 3) (6, 4) >>> print a005185(100) 56 ----------------------------------------------------------------------- """ from itertools import islice, izip, count __all__ = ('a005185_offset', 'a005185_list', 'a005185_list_pairs', 'a005185', 'a005185_gen') __author__ = 'Nick Hobson ' a005185_offset = offset = 1 def a005185_gen(): """Generator function for OEIS sequence A005185.""" a = {1:1, 2:1} yield a[1] yield a[2] for n in count(3): a[n] = a[n-a[n-1]] + a[n-a[n-2]] yield a[n] def a005185_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(a005185_gen(), n)) def a005185_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), a005185_gen())) def a005185(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(a005185_gen(), n-offset, n-offset+1)).pop()