calculating binomial coefficients using itertools

R

Robert Hunter

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) for s in slices]
return l[1:]
 
I

Ian Kelly

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) 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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,905
Latest member
Kristy_Poole

Latest Threads

Top