How to find the most common pair of characters in a string with Python

1 Answer

0 votes
from collections import defaultdict

def findMostCommonPair(s):
    pair_count = defaultdict(int)
    size = len(s)
    
    # Iterate through the string to form pairs
    for i in range(size - 1):
        pair = s[i:i + 2]
        pair_count[pair] += 1
    
    # Find the pair with the highest frequency
    most_common = max(pair_count, key=pair_count.get)
    
    return most_common, pair_count[most_common]


s = "xzvxdeshaalzxzmdenlopxzxzxzaaqdewrzaaaapeerxzxz";

result = findMostCommonPair(s)

print(f"The most common pair is '{result[0]}' with {result[1]} occurrences")



'''
run:

The most common pair is 'xz' with 7 occurrences

'''

 



answered Nov 28, 2024 by avibootz
edited Nov 28, 2024 by avibootz

Related questions

...