All Possible Combinations of a List of Values

All Possible Combinations of a list of Values

try this:

static void Main(string[] args)
{

GetCombination(new List<int> { 1, 2, 3 });
}

static void GetCombination(List<int> list)
{
double count = Math.Pow(2, list.Count);
for (int i = 1; i <= count - 1; i++)
{
string str = Convert.ToString(i, 2).PadLeft(list.Count, '0');
for (int j = 0; j < str.Length; j++)
{
if (str[j] == '1')
{
Console.Write(list[j]);
}
}
Console.WriteLine();
}
}

How to get all possible combinations of a list’s elements?

Have a look at itertools.combinations:

itertools.combinations(iterable, r)

Return r length subsequences of elements from
the input iterable.

Combinations are emitted in lexicographic sort order. So, if the
input iterable is sorted, the
combination tuples will be produced in
sorted order.

Since 2.6, batteries are included!

All possible combinations of elements in a list which are next to each other

You can use a recursive generator function:

stuff = [1, 2, 3, 4]
def get_combos(d, c = []):
yield tuple(c)
if d:
yield from get_combos(d[1:], c+[d[0]])
yield from get_combos(d[1:], [d[0]])

result = set(filter(None, get_combos(stuff)))

Output:

{(1,), 
(2,),
(3,),
(4,),
(1, 2),
(2, 3),
(3, 4),
(1, 2, 3),
(2, 3, 4),
(1, 2, 3, 4)}

Generate possible combination of values from a list

From the output you're giving, it seems you want the combinations and not the permutations.

You can iterate over all possible valid lengths (0 to 3) and create a sequence like that.

import itertools as it

list(it.chain.from_iterable(it.combinations([1, 2, 3], i) for i in range(4)))

will output:

[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]


Related Topics



Leave a reply



Submit