Search code examples
pythonpermutation

Figure out all possible permutations of 3 numbers in N slots [Python]


So I need to figure out a way to get all permutations of 3 numbers, namely 1, 0 and -1 when there are N slots.

So in the case of there being 2 slots (N=2) the function would return:

[
    [1,1],
    [1,0],
    [0,1],
    [0,0],
    [-1,0],
    [0,-1],
    [-1,-1],
    [1,-1],
    [-1,1]
]

Similarly if N = 3 we'd have a result that's quite a bit longer so I'm not going to write it out here.

Honestly not sure how to write a function to accomplish this. If anyone has any suggestions I'd be very open to hearing them!

Worth noting: itertools.permutations doesn't work in this case as if I go above 3 slots it will simply return nothing. Need to find a solution that can work when there are up to 10 slots.


Solution

  • This isn't a question about permutations -- you're looking to generate a Cartesian product! In particular, you're looking to generate {-1, 0, 1} x {-1, 0, 1} x {-1, 0, 1} x ... (repeat with n sets)

    This code snippet computes the above:

    n = 2
    nums = [-1, 0, 1]
    print(list(list(entry) for entry in itertools.product(nums, repeat=n)))