1

Is there an easy way in Python to calculate all possible permutations of a given length with two integers using one or both integers. For example, if my integers are 1 and 2 and I want to calculate all possible permutations of length 3, I should get (111, 112, 121, 122, 211, 212, 221, 222). I thought that itertools.permutations would work, but apparently if the length is > the number of integers, no items are returned.

henrypj
  • 37
  • 4

2 Answers2

1

If what you're looking for is simply:

[(1, 1), (1, 2), (2, 1), (2, 2)]

then see Permutation of x length of 2 characters, and this thread is a duplicate.

If, alternatively, what you're looking for is

[11, 12, 21, 22]

then use:

import itertools as it
print([int(str(i) + str(j)) for i, j in it.product(l, repeat=2)])
[11, 12, 21, 22]
Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
-1
import itertools

length = 3
possible_int = [1,2]
all_permutations = []
for i in range(length+1):
    first = [possible_int[0]]*i
    second = [possible_int[1]]*(length-i)
    permutations = [list(x) for x in itertools.permutations(first+second)]
    for element in permutations:
        if element not in all_permutations:
            all_permutations.append(element)

print(all_permutations)
Piotr Wasilewicz
  • 1,751
  • 2
  • 15
  • 26