r""" Python module for OEIS sequence number A046901. a(n) = a(n-1) - n if a(n-1) > n, else a(n) = a(n-1) + n. Examples of use. ----------------------------------------------------------------------- >>> from a046901 import * >>> print a046901_list(18) [1, 3, 6, 2, 7, 1, 8, 16, 7, 17, 6, 18, 5, 19, 4, 20, 3, 21] >>> print a046901_offset 1 >>> for x in a046901_list_pairs(6): ... print x ... (1, 1) (2, 3) (3, 6) (4, 2) (5, 7) (6, 1) >>> print a046901(4) 2 ----------------------------------------------------------------------- """ from itertools import islice, izip, count __all__ = ('a046901_offset', 'a046901_list', 'a046901_list_pairs', 'a046901', 'a046901_gen') __author__ = 'Nick Hobson ' a046901_offset = offset = 1 def a046901_gen(): """Generator function for OEIS sequence A046901.""" x = 0 for n in count(1): x = x - n if x - n > 0 else x + n yield x def a046901_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(a046901_gen(), n)) def a046901_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), a046901_gen())) def a046901(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(a046901_gen(), n-offset, n-offset+1)).pop()