r""" Python module for OEIS sequence number A005132. Recaman's sequence: a(0) = 0; for n > 0, a(n) = a(n-1) - n if that number is positive and not already in the sequence, otherwise a(n) = a(n-1) + n. Examples of use. ----------------------------------------------------------------------- >>> from a005132 import * >>> print a005132_list(16) [0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9, 24] >>> print a005132_offset 0 >>> for x in a005132_list_pairs(6): ... print x ... (0, 0) (1, 1) (2, 3) (3, 6) (4, 2) (5, 7) >>> print a005132(3) 6 ----------------------------------------------------------------------- """ from itertools import islice, izip, count __all__ = ('a005132_offset', 'a005132_list', 'a005132_list_pairs', 'a005132', 'a005132_gen') __author__ = 'Nick Hobson ' a005132_offset = offset = 0 def a005132_gen(gen): """Generator function for the 'Recaman transform'.""" s, x = set(), 0 gen.next() for t in gen: yield x x = x - t if x - t > 0 and x - t not in s else x + t s.add(x) def a005132_list(n): """Returns a list of the first n >= 0 terms of OEIS sequence A005132.""" if n < 0: raise ValueError, 'Input must be a non-negative integer' return list(islice(a005132_gen(count()), n)) def a005132_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), a005132_gen(count()))) def a005132(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(a005132_gen(count()), n-offset, n-offset+1)).pop()