Skip to content
Advertisement

function to output pairwise of passed letters

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

...

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:

from itertools import combinations

def pairwise_letters(s):
    return list(map(''.join, combinations(s, 2)))
    
print(pairwise_letters("ABC"))

This outputs:

['AB', 'AC', 'BC']
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement