views:

714

answers:

5

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)
+11  A: 

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

from itertools import combinations
combinations(range(10), 4)
Nadia Alramli
Thanks, I could do a lot with this.
A: 
int ra;
for(ra=0,ra<10000;ra++) printf("%04u\n",ra);
dwelch
The Python compiler will surely have a field day with THIS code...;-)
Alex Martelli
+1  A: 

Uhm, you want all the numbers from 0 to 9999 formated with leading zeroes ...

numbers = ( "%04d" % i for i in range(0,10000) )
THC4k
I think he is after combinations not permutations.
Philip Fourie
He says he want all the numbers from 0000 to 9999 and his code actually prints out *most* of them ...
THC4k
He doesn't specify if a number can appear once or many times. Also he doesn't specify if 1234 and 4321 should be one combination or two.
Lennart Regebro
1234 and 4321 I would consider as two separate combinations.
+3  A: 

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.

varzan
+4  A: 

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.

J.F. Sebastian
Didn't know about this. Looks great.