pythoncharactersequences

Find Most Frequent Character(s) in any sequence(list, string, tuple) in python 3+ with for loop


question: 10. Most Frequent Character Write a program that lets the user enter a string and displays the character that appears most frequently in the string.

This is an answer for those who are studying intro to cs with "Starting out with Python" chapter 9 question 10. This question is answered solely with what I have learned in previous chapters of the book. I couldn't find anything similar on this website. This code might be OK for beginners like me, so I want to share it. I know this code looks bad, but it gets job done so... Original code I found on Youtube where it is written in Java, here is a link: https://www.youtube.com/watch?v=dyWYLXKSPus sorry for my broken English!)

string = "a11aawww1cccertgft1tzzzzzz1ggg111"
mylist_char = []
mylist_count = []
char = None
count = 0

for ch in string:
    temp_char = ch
    temp_count = 0
    for ch1 in string:
        if temp_char == ch1:
            temp_count += 1

    if temp_count > count:
        count = temp_count
        char = temp_char
mylist_char.append(char)
mylist_count.append(count)
for x in range(len(string)):
    for ch in string:
        temp_char = ch
        temp_count = 0
        for ch1 in string:
            if temp_char == ch1:
                temp_count += 1
        if temp_count == count and not(temp_char in mylist_char):
            mylist_char.append(temp_char)
            mylist_count.append(temp_count)
for x in range(len(mylist_char)):
    print("Character", mylist_char[x], "occurred", mylist_count[x], "times")

Solution

  • My issue with your solution is that it looks like Java rewritten in Python -- if you want to use Java, use Java. If you want to use Python, take advantage of what it has to offer. I've written a "simple" solution below that doesn't use any sophisticated Python functions (e.g. if I were really writing it, I'd use a defaultdict and a comprehension)

    string = "a11aawww1cccertgft1tzzzzzz1ggg111"
    
    dictionary = {}
    
    for character in list(string):
        if character in dictionary:
            dictionary[character] += 1
        else:
            dictionary[character] = 1
    
    results = []
    
    for key, value in dictionary.items():
        results.append((value, key))
    
    for value, key in reversed(sorted(results)):
        print("Character", key, "occurred", value, "times")