multinomial combinations

  • Thread starter Dr. Phillip M. Feldman
  • Start date
D

Dr. Phillip M. Feldman

I wrote a small generator function that produces multinomial combinations.
(Python's itertools module does ordinary combinations, but not multinomial
combinations). The code essentially works, except that the the last
combination in each tuple is not enclosed in a nested tuple:

In [2]: x= multinomial_combinations(range(7),[2,1,2])

In [3]: x.next()
Out[3]: ((0, 1), (2,), 3, 4)

(The 3 and 4 should be enclosed in a nested tuple).

Any suggestions as to what I'm doing wrong will be appreciated. My code
follows:

def multinomial_combinations(items, ns):

if len(ns) == 1:
for c in itertools.combinations(items, ns[0]):
yield c

else:
for c_first in itertools.combinations(items, ns[0]):
items_remaining= set(items) - set(c_first)
for c_other in multinomial_combinations(items_remaining, ns[1:]):
yield (c_first,) + c_other
 

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,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top