I was wondering if there is any way of getting all combinations of length n from a list of numbers.
For example, if my list is [1, 2, 3, 4]
Adding the recursive function:
def combinations(array, tuple_length, prev_array=[]):
if len(prev_array) == tuple_length:
return [prev_array]
combs = []
for i, val in enumerate(array):
prev_array_extended = prev_array.copy()
prev_array_extended.append(val)
combs += combinations(array[i+1:], tuple_length, prev_array_extended)
return combs
combinations([1, 2, 3, 4], 3)
Outputs:
[[1, 2, 3],
[1, 2, 4],
[1, 3, 4],
[2, 3, 4]]