r""" Python module for OEIS sequence number A000179. Menage numbers: number of permutations s of [0, ..., n-1] such that s(i) != i and s(i) != i+1 (mod n) for all i. a(n) = ((n^2-2*n)*a(n-1) + n*a(n-2) - 4(-1)^n)/(n-2) for n >= 4. Examples of use. ----------------------------------------------------------------------- >>> from a000179 import * >>> print a000179_list(12) [1, 0, 0, 1, 2, 13, 80, 579, 4738, 43387, 439792, 4890741] >>> print a000179_offset 0 >>> for x in a000179_list_pairs(6): ... print x ... (0, 1) (1, 0) (2, 0) (3, 1) (4, 2) (5, 13) >>> a000179_list_upto(10000) [1, 0, 0, 1, 2, 13, 80, 579, 4738] >>> print a000179(4) 2 ----------------------------------------------------------------------- """ from itertools import islice, izip, takewhile, count __all__ = ('a000179_offset', 'a000179_list', 'a000179_list_pairs', 'a000179_list_upto', 'a000179', 'a000179_gen') __author__ = 'Nick Hobson ' a000179_offset = offset = 0 def a000179_gen(): """Generator function for OEIS sequence A000179.""" yield 1 yield 0 x, y = 0, 1 for n in count(4): yield x x, y = y, (n*(n-2)*y + n*x - 4*(-1)**n) / (n-2) def a000179_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(a000179_gen(), n)) def a000179_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), a000179_gen())) def a000179_list_upto(m): """Returns a list of all terms not exceeding m >= 0.""" if m < 0: raise ValueError, 'Input must be a non-negative integer' return list(takewhile(lambda t: t <= m, a000179_gen())) def a000179(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(a000179_gen(), n-offset, n-offset+1)).pop()