-1

I have a list something like this and I want all combinations for two point solution

list1=['a','b','c','d','e','f','g','h']

and I need all 28 combinations from this Expected result:

[['a','b'],['a','c'],['a','d'],['a','e'],['a','f'],['a','g'],['a','h'],
['b','c'],['b','d'],['b','e'],['b','f'],['b','g'],['b','h'],
['c','d'],['c','e'],['c','f'],['c','g'],['c','h'],
['d','e'],['d','f'],['d','g'],['d','h'],
['e','f'],['e','g'],['e','h'],
['f','g'],['f','h'],
['g','h']]

This link is explanation of how 28 combinations. https://www.calculatorsoup.com/calculators/discretemathematics/combinations.php

I have tried scipy

from scipy.special import comb
comb(8, 2, exact=True)

but it is not giving me the actual combination, It is giving me number of possible combination.

itertools is giving me memory error. as in my list df["ID"] there would be more than 1000 elements.

len(list(combinations(df["ID"].to_list(),5)))

If the I want three point solution then possible combination would be 56

Thanks for your help

Nirali Khoda
  • 1,661
  • 1
  • 7
  • 26
  • You say you get a memory error, but is your goal to count how many options there are, to print the to a file, or what? Doing `list()` fully expands the list in memory, while `itertools.combinations` probably does its work without storing the full list in memory. So you might need to iterate directly on it instead of casting it to a list. – joanis Mar 12 '21 at 17:31
  • Hi @joanis I need the the list of all this combination and make a data frame out of that for further calculations. – Nirali Khoda Mar 15 '21 at 06:23
  • In that case, I would think your problem is that you need to allocate more memory to your process, because I'm pretty sure the itertools solution is right. Or maybe you could change your code so that the further calculations also use itertools instead of storing the list in memory. – joanis Mar 15 '21 at 12:20

1 Answers1

1

Using itertools.combinations returns 28 combinations.

itertools.combinations(list1, 2)

#[('a', 'b'), ('a', 'c'), ('a', 'd'), ('a', 'e'), ('a', 'f'), ('a', 'g'), ('a', 'h'), ('b', 'c'), ('b', 'd'), ('b', 'e'), ('b', 'f'), ('b', 'g'), ('b', 'h'), ('c', 'd'), ('c', 'e'), ('c', 'f'), ('c', 'g'), ('c', 'h'), ('d', 'e'), ('d', 'f'), ('d', 'g'), ('d', 'h'), ('e', 'f'), ('e', 'g'), ('e', 'h'), ('f', 'g'), ('f', 'h'), ('g', 'h')]

len(list(itertools.combinations(list1, 2)))
#28
PacketLoss
  • 5,561
  • 1
  • 9
  • 27
  • Maybe they tried to use `itertools.permutations`? That would yield 56 results, but it would be strange, since the question text suggests that they know the difference between permutations and combinations. – Håken Lid Mar 12 '21 at 12:10
  • @PacketLoss it is giving me proper solution but I am getting memory error. – Nirali Khoda Mar 12 '21 at 12:30
  • @NiraliKhoda https://stackoverflow.com/a/58664678/7942856 – PacketLoss Mar 12 '21 at 12:35