I would like to create a Python function that can take in letters and output a pairwise comparison of the letter given.
So for example, if my function is named pairwise_letters()
, then it should behave as follows:
JavaScript
x
27
27
1
>>> pairwise_letters('AB')
2
AB
3
4
>>> pairwise_letters('ABC')
5
AB BC
6
AC
7
8
>>> pairwise_letters('ABCD')
9
AB BC CD
10
AC BD
11
AD
12
13
>>> pairwise_letters('ABCDE')
14
AB BC CD DE
15
AC BD CE
16
AD BE
17
AE
18
19
>>> pairwise_letters('ABCDEF')
20
AB BC CD DE EF
21
AC BD CE DF
22
AD BE CF
23
AE BF
24
AF
25
26
27
Advertisement
Answer
Use itertools.combinations()
to get each pairing. By default, itertools.combinations()
outputs an iterable of tuples, which you’ll need to massage a bit to turn into a list of strings:
JavaScript
1
7
1
from itertools import combinations
2
3
def pairwise_letters(s):
4
return list(map(''.join, combinations(s, 2)))
5
6
print(pairwise_letters("ABC"))
7
This outputs:
JavaScript
1
2
1
['AB', 'AC', 'BC']
2