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]
, and I want to output (if I chose n = 3)
[1, 2, 3] [1, 2, 4] [1, 3, 4] [2, 3, 4]
the other permutations like [2,1,3] are of no use to me.
Add a Custom Column to and name it List1. Enter the formula =List1. Expand out the new List1 column and then Close & Load the query to a table. The table will have all the combinations of items from both lists and we saved on making a custom column in List1 and avoided using a merge query altogether!
itertools
can do this:
import itertools for comb in itertools.combinations([1, 2, 3, 4], 3): print(comb)
Outputs:
(1, 2, 3) (1, 2, 4) (1, 3, 4) (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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With