I'm working with lists in Python.
I have a list of colleagues which is
colleagues=['Jack', 'Jessica' 'John', 'Mark', 'Mary', 'Paul']
- I want to calculate all possible couples (i.e. combination without repetition, order does not matter). That means this result:
couples=[['Jack', 'Jessica'], ['Jack', 'John'], ['Jack', 'Mark'], ['Jack', 'Mary'], ['Jessica', 'John'], ['Jessica', 'Mark'], ['Jessica', 'Mary'], ['John', 'Mark'], ['John', 'Mary'], ['Mark', 'Mary'], ['Jack', 'Paul'], ['Jessica','Paul'], ['John','Paul'], ['Mark','Paul'], ['Mary','Paul']]
- Then, I want the couples to be split into n-1 dates where they would meet each other (therefore, every person appears only once every day) That is sort of:
Day | Meeting_1 | Meeting_2 | Meeting_3 |
---|---|---|---|
0 | 'Jack', 'Jessica' | 'John', 'Mark' | 'Mary','Paul' |
1 | 'Jack', 'John' | 'Mark', 'Mary' | 'Jessica','Paul' |
2 | 'Jack', 'Mark' | 'John','Paul' | 'Jessica', 'Mary' |
3 | 'Jack', 'Mary' | 'Jessica', 'John' | 'Mark','Paul' |
4 | 'Jack', 'Paul' | 'Jessica', 'Mark' | 'John', 'Mary' |
How can I do it? Also, I need a code that works for whatever n and k in the combination.
Thanks in advance and please, ask if there's a missing input you need. I will provide you with everything.
Cheers
CodePudding user response:
The formula should be n!/((n-k)!*k!). So applied in python it should be something like this.
def couples(lst):
l = []
for i in range(len(lst)):
for j in range(i 1,len(lst)):
l.append([lst[i],lst[j]])
return l
CodePudding user response:
You can try a recursive couple generator:
def couples(l):
if not l:
yield []
for a in ((l[0],x) for x in l[1:]):
for b in couples([x for x in l if x not in a]):
yield [a] b
pd.DataFrame(couples(colleagues))
Output:
0 1 2
0 (Jack, Jessica) (John, Mark) (Mary, Paul)
1 (Jack, Jessica) (John, Mary) (Mark, Paul)
2 (Jack, Jessica) (John, Paul) (Mark, Mary)
3 (Jack, John) (Jessica, Mark) (Mary, Paul)
4 (Jack, John) (Jessica, Mary) (Mark, Paul)
5 (Jack, John) (Jessica, Paul) (Mark, Mary)
6 (Jack, Mark) (Jessica, John) (Mary, Paul)
7 (Jack, Mark) (Jessica, Mary) (John, Paul)
8 (Jack, Mark) (Jessica, Paul) (John, Mary)
9 (Jack, Mary) (Jessica, John) (Mark, Paul)
10 (Jack, Mary) (Jessica, Mark) (John, Paul)
11 (Jack, Mary) (Jessica, Paul) (John, Mark)
12 (Jack, Paul) (Jessica, John) (Mark, Mary)
13 (Jack, Paul) (Jessica, Mark) (John, Mary)
14 (Jack, Paul) (Jessica, Mary) (John, Mark)