"""
Mosaics using Python generators...
by K. Urner
4dsolutions.net
based on a thread on mathfuture:
http://groups.google.com/group/mathfuture/msg/9d098696c2ea7426?hl=en

Just as the Fibonacci sequence generator might be "seeded" by any
two integers to start off, so might Pascal's Triangle be seeded with
any beginning row.

When these sequences are formed into tabular or other areal displays,
such that information may be gleaned from rows and columns, these
formats may be called "mosaics" in some of the literature.
"""

def fibonacci( a=0, b=1):
    """
    Generator for a Fibonacci sequence starting from any two integers

    See:  Online Encyclopedia of Integer Sequences
    http://oeis.org/A000045

    >>> gen = fibonacci()
    >>> [next(gen) for i in range(11)]
    [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
    >>> gen = fibonacci(-1, 2)
    >>> [next(gen) for i in range(11)]
    [-1, 2, 1, 3, 4, 7, 11, 18, 29, 47, 76]
    """

    while True:
        yield a
        b, a = a + b, b


def pascal( therow = [1]):
    """
    Generator for Pascal's Triangle starting from any top row

    Enter list for top row

    See:  Number Mosaics by Adi R. Kanga  (pg. 29, Fig 20)
    http://bit.ly/gDmmAo

    >>> gen = pascal([15, 20, 6])
    >>> next(gen)
    [15, 20, 6]
    >>> next(gen)
    [15, 35, 26, 6]
    >>> next(gen)
    [15, 50, 61, 32, 6]
    >>> next(gen)
    [15, 65, 111, 93, 38, 6]
    >>> next(gen)
    [15, 80, 176, 204, 131, 44, 6]
    >>> next(gen)
    [15, 95, 256, 380, 335, 175, 50, 6]
    """
    while True:
        yield therow
        therow = [ i + j for i, j in zip(therow + [0], [0] + therow) ]

def _test():
    import doctest
    doctest.testmod()

if __name__ == "__main__":
        _test()
_______________________________________________
Edu-sig mailing list
Edu-sig@python.org
http://mail.python.org/mailman/listinfo/edu-sig

Reply via email to