I need to generate permutations of digits, the number can be bigger than the digit count. For my current purpose I need to generate permutations of these digits 0, 1, 2
What you are looking is called a Cartesian product, not a permutation. Python itertools have a method itertools.product() to produce the desired result:
import itertools
for p in itertools.product(range(3), repeat=4):
print p
Output is 3^4 lines:
(0, 0, 0, 0)
(0, 0, 0, 1)
(0, 0, 0, 2)
(0, 0, 1, 0)
(0, 0, 1, 1)
...
(2, 2, 2, 1)
(2, 2, 2, 2)
To produce output tuples with length form 1 to 4, use an additional iteration:
for l in range(1, 5):
for p in itertools.product(range(3), repeat=l):
print p
Finally, this works for string elements, too:
for i in range(5):
for p in itertools.product(('0', '1', '2'), repeat=i):
print ''.join(p),
print
Output:
0 1 2 00 01 02 10 11 12 20 21 22 000 001 002 010 [...] 2220 2221 2222