Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,988 questions

51,933 answers

573 users

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

...