0

There are many examples how to get all combinations of n items of length l, if l <= n. But how about get all combinations of n items (f.i. digits) of lenght l, where n < l, for instance:

n = 3 ([0,1,2])
l = 5
sequence to get:
00000
00001
00002
00010
...
22222

It is not a problem to implement it, but I suppose it is possible to do using itertools. I can not find how.

2 Answers2

1

From itertools documentation :

product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111

So for your case the code will be

itertools.product(range(3), repeat=5)
ssh
  • 147
  • 1
  • 3
  • thank you so much! that is exactly what i was looking for. – user9893356 Feb 23 '19 at 17:39
  • I have implemented my own variant today, and it is 3x faster. It counts for me, so I will use my implementation, not from itertools. I think I could rewrite itertools implementation to run a little prompter. – user9893356 Feb 24 '19 at 20:58
0

Since this set is essentially just a ternary number system, we can use a ternary function from here

def ternary (n):
    if n == 0:
        return '0'
    nums = []
    while n:
        n, r = divmod(n, 3)
        nums.append(str(r))
    return ''.join(reversed(nums))

And you can treat this as an array, and iterate to it through a for loop that goes something like this:

for i in range(3**5):
    print(ternary(i))
Shipof123
  • 233
  • 2
  • 11