Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all combinations of length n in python

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.

like image 498
user3685412 Avatar asked Jan 15 '15 22:01

user3685412


People also ask

How do you generate all possible combinations of one list?

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!


2 Answers

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) 
like image 104
jlb83 Avatar answered Oct 03 '22 19:10

jlb83


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]] 
like image 35
RoyR Avatar answered Oct 03 '22 19:10

RoyR