Reputation: 3624
As a part of my project, I need to group characters as pairs (unique). I have more than 1000 of these characters in a list. What would be the fastest and optimized method to create unique pairs out of these list of characters. I am using itertools currently and my code seems to perform pretty badly.
My Code using itertools:
import itertools
characters = ['A', 'B', 'C', 'D', 'E']
relations = []
for character in range(len(characters) + 1):
for combination in itertools.combinations(characters, character):
if len(combination) == 2:
relations.append(combination)
print relations
Expected Output:
[('A', 'B'), ('A', 'C'), ('A', 'D'), ('A', 'E'), ('B', 'C'),
('B', 'D'), ('B', 'E'), ('C', 'D'), ('C', 'E'), ('D', 'E')]
Upvotes: 1
Views: 271
Reputation: 62908
All you need are combinations of length 2?
In [48]: characters = ['A', 'B', 'C', 'D', 'E']
In [50]: list(itertools.combinations(characters, 2))
Out[50]:
[('A', 'B'),
('A', 'C'),
('A', 'D'),
('A', 'E'),
('B', 'C'),
('B', 'D'),
('B', 'E'),
('C', 'D'),
('C', 'E'),
('D', 'E')]
You are also generating combinations of length 3 to len(characters) and throwing them all away.
characters = ['A', 'B', 'C', 'D', 'E']
relations = list(itertools.combinations(characters, 2))
Upvotes: 5