There is a code:

import itertools for i in itertools.combinations_with_replacement('0123456789', 4): print(''.join(i)) 

I need to get all combinations of numbers in 4 repetitions. Part of the output of the program:

 0000 0001 0002 0003 0004 0005 0006 0007 0008 0009 0011 0012 0013 0014 0015 0016 0017 0018 0019 0022 0023 0024 0025 

Tell me why after 0009 is 0011 , and not 0010 ? Also from 0022 .

  • one
    because the code does not distinguish between 01 and 10 (the difference between the combination and the permutation). What's the problem with for i in range(10**4):print("%04d" % i) - jfs

1 answer 1

Because for your task you need to take not combinations_with_replacement , but product :

 import itertools for i in itertools.product('0123456789', repeat=4): print(''.join(i)) 

Combinations in combinatorics do not take into account the order of the elements. Therefore, a set of the same elements will be considered the same combination, even if the elements are in a different order. Your code has already printed a combination of three zeros and one unit (0001) once, so it will not print other variants of this combination — 0010, 0100, and 1000. The same with other numbers.

  • Thank you, everything is clear) - Garviel Loken pm