r""" Python module for OEIS sequence number A064387. Variation (2) 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 a(n) = a(n-1) + n+i, where i >= 0 is the smallest number such that a(n-1) + n+i has not already appeared. Examples of use. ----------------------------------------------------------------------- >>> from a064387 import * >>> print a064387_list(15) [1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9, 24] >>> print a064387_offset 1 >>> for x in a064387_list_pairs(6): ... print x ... (1, 1) (2, 3) (3, 6) (4, 2) (5, 7) (6, 13) >>> print a064387(7) 20 ----------------------------------------------------------------------- """ from itertools import islice, izip, count __all__ = ('a064387_offset', 'a064387_list', 'a064387_list_pairs', 'a064387', 'a064387_gen') __author__ = 'Nick Hobson ' a064387_offset = offset = 1 def a064387_gen(): """Generator function for OEIS sequence A064387.""" s, x = set(), 0 for n in count(1): if x - n > 0 and x - n not in s: x -= n else: x += n while x in s: x += 1 s.add(x) yield x def a064387_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(a064387_gen(), n)) def a064387_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), a064387_gen())) def a064387(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(a064387_gen(), n-offset, n-offset+1)).pop()