calculating binomial coefficients using itertools

Ian Kelly ian.g.kelly at gmail.com
Sat Jul 6 03:11:01 EDT 2013


On Fri, Jul 5, 2013 at 4:58 PM, Robert Hunter <bobjim.hunter at gmail.com> wrote:
> from itertools import count, repeat, izip, starmap
>
> def binomial(n):
>     """Calculate list of Nth-order binomial coefficients using itertools."""
>
>     l = range(2)
>     for _ in xrange(n):
>         indices = izip(count(-1), count(1), repeat(1, len(l) + 1))
>         slices = starmap(slice, indices)
>         l = [sum(l[s]) for s in slices]
>     return l[1:]

Nice, I like seeing interesting ways to use slice.  This will be more
efficient, though:

def binomial(n):
    value = 1
    for i in range(n+1):
        yield value
        value = value * (n-i) // (i+1)



More information about the Python-list mailing list