Maximum number of combinations

I am trying to create a list of all possible combinations of numbers in a set of four numbers, using all numbers from 0 to 9.

I’m getting closer, but the output does not display all possible combinations, starting from 0000 to 9999.

Any hints as to why the following code discards 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)
+3
source share
4 answers

This line:

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

Basically you say: "Get a number, than add another one other than ir, repeat n times, then return a list of these numbers. This will give you numbers where the numbers will not be displayed more than once. This line:

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

then you get all the combinations.

+4
source

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

from itertools import combinations
combinations(range(10), 4)
+12
source

itertools:

>>> 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 Python 3.1 ( 2.7).

, itertools.product .

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

Source: https://habr.com/ru/post/1717013/