r""" Python module for OEIS sequence number A064389. Variation (4) on Recaman's sequence (A005132): to get a(n), we first try to subtract n from a(n-1): a(n) = a(n-1) - n if positive and not already in the sequence; if not then we try to add n: a(n) = a(n-1) + n if not already in the sequence; if this fails we try to subtract n+1 from a(n-1), or to add n+1 to a(n-1), or to subtract n+2, or to add n+2, etc., until one of these produces a positive number not already in the sequence - this is a(n). Examples of use. ----------------------------------------------------------------------- >>> from a064389 import * >>> print a064389_list(15) [1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9, 24] >>> print a064389_offset 1 >>> for x in a064389_list_pairs(6): ... print x ... (1, 1) (2, 3) (3, 6) (4, 2) (5, 7) (6, 13) >>> print a064389(7) 20 ----------------------------------------------------------------------- """ from itertools import islice, izip, count __all__ = ('a064389_offset', 'a064389_list', 'a064389_list_pairs', 'a064389', 'a064389_gen') __author__ = 'Nick Hobson ' a064389_offset = offset = 1 def a064389_gen(): """Generator function for OEIS sequence A064389.""" s, x = set(), 0 for n in count(1): y = x m = -n x = y + m while not (x > 0 and x not in s): m = -m if m < 0 else -(m + 1) x = y + m s.add(x) yield x def a064389_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(a064389_gen(), n)) def a064389_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), a064389_gen())) def a064389(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(a064389_gen(), n-offset, n-offset+1)).pop()