Python SciPy Possible Cases n Choose k

a = [1, 2, 3, 4, 5, 6] # OR ! a = ['one', 'two', 'three', 'four', 'five', 'six'] 

In this situation, I just want to know ALL possible combinations; select k items from a . If I use b = scipy.misc.comb(a, 1) , it shows:

 b = [1, 2, 3, 4, 5, 6] 

where b i is just i select 1. And it does not work if a is an array of strings.

I really wanted to:

 b = [[1], [2], [3], [4], [5], [6]] # OR ! b = [['one'], ['two'], ['three'], ['four'], ['five'], ['six']] 

which means that a possible set of 1 selected element among the elements of the array a

It is very easy if I use MATLAB. But I'm trying to use the SciPy stack.

+4
source share
2 answers

Any reason to use scipy rather than itertools for this particular problem?

The inclusion of itertools.combinations or itertools.permutations may provide a more appropriate solution.

+7
source

Here is a more complete answer. You should use itertools.combinations , not itertools.permutations , since the combination is very different from permutation.

For example, if you need all two combinations of array elements, such as [1,2,3,5] , the following code will give the result you want (equivalent to nchoosek in Matlab). Additional examples from this source .

 >>> import itertools >>> all_combos = list(itertools.combinations([1,2,3,5], 2)) >>> print all_combos [(1, 2), (1, 3), (1, 5), (2, 3), (2, 5), (3, 5)] 

if you want all combinations as a 2d array to just convert the list of tuples to a numpy array using the following command:

 >>> all_combos = np.array(list(itertools.combinations([1,2,3,5], 2))) >>> print all_combos [[1 2] [1 3] [1 5] [2 3] [2 5] [3 5]] 
+4
source

Source: https://habr.com/ru/post/1499375/


All Articles