问题
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)
回答1:
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.
回答2:
If you have python 2.6, why not use itertools.combinations?
from itertools import combinations
combinations(range(10), 4)
回答3:
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.
回答4:
int ra;
for(ra=0,ra<10000;ra++) printf("%04u\n",ra);
来源:https://stackoverflow.com/questions/1385929/maximum-number-combinations