Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

...

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading