Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading