Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #50026 > unrolled thread

calculating binomial coefficients using itertools

Started byRobert Hunter <bobjim.hunter@gmail.com>
First post2013-07-05 15:58 -0700
Last post2013-07-06 01:11 -0600
Articles 2 — 2 participants

Back to article view | Back to comp.lang.python


Contents

  calculating binomial coefficients using itertools Robert Hunter <bobjim.hunter@gmail.com> - 2013-07-05 15:58 -0700
    Re: calculating binomial coefficients using itertools Ian Kelly <ian.g.kelly@gmail.com> - 2013-07-06 01:11 -0600

#50026 — calculating binomial coefficients using itertools

FromRobert Hunter <bobjim.hunter@gmail.com>
Date2013-07-05 15:58 -0700
Subjectcalculating binomial coefficients using itertools
Message-ID<5d22d723-bf1b-467d-b9d3-a9a814230309@googlegroups.com>
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:]

[toc] | [next] | [standalone]


#50049

FromIan Kelly <ian.g.kelly@gmail.com>
Date2013-07-06 01:11 -0600
Message-ID<mailman.4328.1373094710.3114.python-list@python.org>
In reply to#50026
On Fri, Jul 5, 2013 at 4:58 PM, Robert Hunter <bobjim.hunter@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)

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web