Let's say , I have following even number names list and should return representing pairs as result :
['A', 'B', 'C', 'D']
>>> [[('B', 'C'), ('A', 'D')],
[('A', 'B'), ('C', 'D')],
[('A', 'C'), ('B', 'D')]]
I wrote the following code :
import itertools
combinations = list(itertools.combinations(['A', 'B', 'C', 'D'], 2))
result = []
for i in range( 0 , len(combinations) ):
if (combinations[i-1][0] != combinations[i][0]) & (combinations[i-1][0] != combinations[i][1]) :
if (combinations[i-1][1] != combinations[i][0]) & (combinations[i-1][1] != combinations[i][1]) :
zipped = zip(combinations[i], combinations[i-1])
result.append(list(zipped))
result
But it gives following as a result ;
[[('A', 'C'), ('B', 'D')],
[('B', 'A'), ('C', 'D')]]
What is the missing point in my code ?
CodePudding user response:
This is a tricky little problem, especially when extended to more than four names. What I've done here is to create all the permutations of the four names. Then, to determine uniqueness, I sort the pairs, and sort the list of pairs. I then keep the unique ones.
import itertools
gather = []
for sets in itertools.permutations(['Andrea', 'Bob', 'Cassandra', 'Doug']):
pairs = sorted([sorted(p) for p in zip(sets[0::2],sets[1::2])])
if pairs not in gather:
gather.append(pairs)
from pprint import pprint
pprint(gather)
Output for four names:
[[['Andrea', 'Bob'], ['Cassandra', 'Doug']],
[['Andrea', 'Cassandra'], ['Bob', 'Doug']],
[['Andrea', 'Doug'], ['Bob', 'Cassandra']],
Output for six names:
[[['Andrea', 'Bob'], ['Cassandra', 'Doug'], ['Ethel', 'Fred']],
[['Andrea', 'Bob'], ['Cassandra', 'Ethel'], ['Doug', 'Fred']],
[['Andrea', 'Bob'], ['Cassandra', 'Fred'], ['Doug', 'Ethel']],
[['Andrea', 'Cassandra'], ['Bob', 'Doug'], ['Ethel', 'Fred']],
[['Andrea', 'Cassandra'], ['Bob', 'Ethel'], ['Doug', 'Fred']],
[['Andrea', 'Cassandra'], ['Bob', 'Fred'], ['Doug', 'Ethel']],
[['Andrea', 'Doug'], ['Bob', 'Cassandra'], ['Ethel', 'Fred']],
[['Andrea', 'Doug'], ['Bob', 'Ethel'], ['Cassandra', 'Fred']],
[['Andrea', 'Doug'], ['Bob', 'Fred'], ['Cassandra', 'Ethel']],
[['Andrea', 'Ethel'], ['Bob', 'Cassandra'], ['Doug', 'Fred']],
[['Andrea', 'Ethel'], ['Bob', 'Doug'], ['Cassandra', 'Fred']],
[['Andrea', 'Ethel'], ['Bob', 'Fred'], ['Cassandra', 'Doug']],
[['Andrea', 'Fred'], ['Bob', 'Cassandra'], ['Doug', 'Ethel']],
[['Andrea', 'Fred'], ['Bob', 'Doug'], ['Cassandra', 'Ethel']],
[['Andrea', 'Fred'], ['Bob', 'Ethel'], ['Cassandra', 'Doug']]]