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:
>>> pairwise_letters('AB')
AB
>>> pairwise_letters('ABC')
AB BC
AC
>>> pairwise_letters('ABCD')
AB BC CD
AC BD
AD
>>> pairwise_letters('ABCDE')
AB BC CD DE
AC BD CE
AD BE
AE
>>> pairwise_letters('ABCDEF')
AB BC CD DE EF
AC BD CE DF
AD BE CF
AE BF
AF
...
CodePudding user response:
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:
from itertools import combinations
def pairwise_letters(s):
return list(map(''.join, combinations(s, 2)))
print(pairwise_letters("ABC"))
This outputs:
['AB', 'AC', 'BC']
CodePudding user response:
does this function behave as you expect?:
def pairwise_letters(s):
for i in range(len(s)):
print(*[''.join(j) for j in zip(s, s[i 1:])], sep=' ')
pairwise_letters('ABCDEF')
'''
AB BC CD DE EF
AC BD CE DF
AD BE CF
AE BF
AF