I’m trying to create an array of all possible combinations of three or more pairs of numbers. For example, given the pairs [11,1], [9,9], [11,1]
, I need the array
[[11, 9, 11],
[11, 9, 11],
[ 1, 9, 11],
[ 1, 9, 11],
[11, 9, 1],
[11, 9, 1],
[ 1, 9, 1],
[ 1, 9, 1]]
I have a function that takes an array of pairs as input, but for some reason it does not output the expected result.
Is there a way to store the input pair information as a variable and use it in a function to produce the desired output?
import numpy as np
def generate_combinations(pairs):
# Return array of all possible combinations of the given pairs
return np.array(np.meshgrid(*pairs)).T.reshape(-1, len(pairs))
Example usage:
pairs = [[11,1], [9,9], [11,1]]
combinations = generate_combinations(pairs)