r""" Python module for OEIS sequence number A057167. Term in Recaman's sequence A005132 where n appears for first time, or 0 if n never appears. Examples of use. ----------------------------------------------------------------------- >>> from a057167 import * >>> print a057167_list(15) [1, 4, 2, 131, 129, 3, 5, 16, 14, 12, 10, 8, 6, 31, 29] >>> # Calculate at most 130 terms of A005132; return None if n has not appeared. >>> print a057167_list(15, 130) [1, 4, 2, None, 129, 3, 5, 16, 14, 12, 10, 8, 6, 31, 29] >>> # Calculate at most 131 terms of A005132; return None if n has not appeared. >>> print a057167_list(15, 131) [1, 4, 2, 131, 129, 3, 5, 16, 14, 12, 10, 8, 6, 31, 29] >>> print a057167_offset 1 >>> for x in a057167_list_pairs(6): ... print x ... (1, 1) (2, 4) (3, 2) (4, 131) (5, 129) (6, 3) >>> print a057167(4) 131 >>> # Calculate at most 100 terms of A005132; return None if 4 has not appeared. >>> print a057167(4, 130) None >>> # Calculate at most 200 terms of A005132; return None if 4 has not appeared. >>> print a057167(4, 131) 131 ----------------------------------------------------------------------- """ from itertools import islice, izip, count from a005132 import a005132_gen __all__ = ('a057167_offset', 'a057167_list', 'a057167_list_pairs', 'a057167', 'a005132_gen') __author__ = 'Nick Hobson <nickh@qbyte.org>' a057167_offset = offset = 1 def a057167_list(n, p=None): """Returns a list of the first n >= 0 terms. If parameter p is passed, at most p iterations are performed; if n has not appeared then a(n) is set to None. """ if n < 0: raise ValueError, 'Input n must be a non-negative integer' if p is not None and p < 1: raise ValueError, 'Input p must be a positive integer' prange = count() if p is None else xrange(p+1) r, t = [None] * n, 0 for (k, x) in izip(prange, a005132_gen(count())): if 0 < x <= n and r[x-1] is None: r[x-1] = k t += 1 if t == n: break return r def a057167_list_pairs(n, p=None): """Returns a list of tuples (n, a(n)) of the first n >= 0 terms. If parameter p is passed, at most p iterations are performed; if n has not appeared then a(n) is set to None. """ if n < 0: raise ValueError, 'Input n must be a non-negative integer' if p is not None and p < 1: raise ValueError, 'Input p must be a positive integer' return list(izip(xrange(offset, n+offset), a057167_list(n, p))) def a057167(n, p=None): """Returns the term with index n >= 1; offset 1. If parameter p is passed, at most p iterations are performed; if n has not appeared then a(n) is set to None. """ if n < offset: raise ValueError, 'Input n must be an integer >= offset = ' + str(offset) if p is not None and p < 1: raise ValueError, 'Input p must be a positive integer' prange = count() if p is None else xrange(p+1) for (k, x) in izip(prange, a005132_gen(count())): if x == n: return k return None