Getting all possible combinations from a list of numbers

Not my code, but you’re looking for the powerset. Google gave me this solution, which seems t work: public IEnumerable<IEnumerable<T>> GetPowerSet<T>(List<T> list) { return from m in Enumerable.Range(0, 1 << list.Count) select from i in Enumerable.Range(0, list.Count) where (m & (1 << i)) != 0 select list[i]; } Source: http://rosettacode.org/wiki/Power_set#C.23

N-D version of itertools.combinations in numpy

You can use itertools.combinations() to create the index array, and then use NumPy’s fancy indexing: import numpy as np from itertools import combinations, chain from scipy.special import comb def comb_index(n, k): count = comb(n, k, exact=True) index = np.fromiter(chain.from_iterable(combinations(range(n), k)), int, count=count*k) return index.reshape(-1, k) data = np.array([[1,2,3,4,5],[10,11,12,13,14]]) idx = comb_index(5, 3) print(data[:, idx]) output: … Read more

How to generate all the permutations of a multiset?

Generating all the possible permutations and then discarding the repeated ones is highly inefficient. Various algorithms exist to directly generate the permutations of a multiset in lexicographical order or other kind of ordering. Takaoka’s algorithm is a good example, but probably that of Aaron Williams is better http://webhome.csc.uvic.ca/~haron/CoolMulti.pdf moreover, it has been implemented in the … Read more

Generating permutations lazily

Yes, there is a “next permutation” algorithm, and it’s quite simple too. The C++ standard template library (STL) even has a function called next_permutation. The algorithm actually finds the next permutation — the lexicographically next one. The idea is this: suppose you are given a sequence, say “32541”. What is the next permutation? If you … Read more

How do I generate all permutations of a list?

Use itertools.permutations from the standard library: import itertools list(itertools.permutations([1, 2, 3])) Adapted from here is a demonstration of how itertools.permutations might be implemented: def permutations(elements): if len(elements) <= 1: yield elements return for perm in permutations(elements[1:]): for i in range(len(elements)): # nb elements[0:1] works in both string and list contexts yield perm[:i] + elements[0:1] + … Read more

Nth Combination

Note you can generate the sequence by recursively generating all combinations with the first element, then all combinations without. In both recursive cases, you drop the first element to get all combinations from n-1 elements. In Python: def combination(l, r): if r == 0: yield [] elif len(l) == r: yield l else: for c … Read more