3

I am trying to generate a list of all possible number combinations within a set of four numbers using all numbers from 0 through 9.

I'm getting close but the output doesn't show every possible combination starting from 0000 all the way to 9999.

Any clues as to why the following code is dropping certain combinations?

def permgen(items, n):
  if n==0: yield []
    else:
        for i in range(len(items)):
            for cc in permgen(items[:i]+items[i+1:],n-1):
                yield [items[i]]+cc

if __name__=="__main__":
    for c in permgen(['0','1','2','3','4','5','6','7','8','9'],4): print ''.join(c)
2
  • 1
    Can a number appear more than once? Is 1234 a different combination than 1243? Commented Sep 6, 2009 at 17:00
  • Yes, those would be two separate combinations. Commented Sep 6, 2009 at 18:04

4 Answers 4

12

If you have python 2.6, why not use itertools.combinations?

from itertools import combinations
combinations(range(10), 4)
Sign up to request clarification or add additional context in comments.

Comments

4

This line:

for cc in permgen(items[:i]+items[i+1:],n-1):

You're basically saying "get a number, than add another one different from ir, repeat n times, then return a list of these digits. That's going to give you numbers where no digit appears more than once. If you change that line to:

for cc in permgen(items,n-1):

then you get all combinations.

Comments

4

Take a look at itertools' combinatoric generators:

>>> from itertools import combinations, permutations, product
>>> def pp(chunks):
...     print(' '.join(map(''.join, chunks)))
...
>>> pp(combinations('012', 2))
01 02 12
>>> pp(permutations('012', 2))
01 02 10 12 20 21
>>> pp(product('012', repeat=2))
00 01 02 10 11 12 20 21 22
>>> from itertools import combinations_with_replacement
>>> pp(combinations_with_replacement('012', 2))
00 01 02 11 12 22

combinations_with_replacement is available in Python 3.1 (or 2.7).

It seems that itertools.product is the most suitable for your task.

Comments

0
int ra;
for(ra=0,ra<10000;ra++) printf("%04u\n",ra);

1 Comment

The Python compiler will surely have a field day with THIS code...;-)