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

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

How to display string letters sorted by frequency in Python

1 Answer

0 votes
# sortByFrequency — counts how often each letter appears and returns a sorted list
def sortByFrequency(s: str):
    # Create a frequency array for 26 lowercase letters, initialized to 0
    freq = [0] * 26

    # Iterate through the string and count only alphabetic characters
    for c in s:
        if c.isalpha():
            # Convert to lowercase and map 'a'..'z' to 0..25
            freq[ord(c.lower()) - ord('a')] += 1

    # Build a list of (letter, frequency) pairs
    result = [(chr(ord('a') + i), freq[i]) for i in range(26)]

    # Sort pairs by frequency in descending order
    result.sort(key=lambda p: p[1], reverse=True)

    return result


# Build a string sorted by frequency: ddddddddddddccccccbbbbbaaaafffeehhgs
def buildSortedString(sorted_list):
    out = []

    for letter, count in sorted_list:
        # append 'letter' repeated count times
        if count > 0:
            out.append(letter * count)

    return "".join(out)


def main():
    # Input text to analyze
    text = "bbcabddddccafffadbbcdccsedddddhhgade"

    # Get sorted frequency list
    sorted_list = sortByFrequency(text)

    # Print each letter and its frequency
    for letter, count in sorted_list:
        if count != 0:
            print(f"{letter}: {count}")

    # Print the reconstructed sorted string
    letters_sorted_by_frequency = buildSortedString(sorted_list)
    print("\nSorted string:", letters_sorted_by_frequency)


if __name__ == "__main__":
    main()


"""
run:

d: 12
c: 6
b: 5
a: 4
f: 3
e: 2
h: 2
g: 1
s: 1

Sorted string: ddddddddddddccccccbbbbbaaaafffeehhgs

"""

 



answered Jul 3 by avibootz
...