Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In Python, Return the most frequent character in a string and the frequency of t

ID: 3702718 • Letter: I

Question

In Python, Return the most frequent character in a string and the frequency of the character. Call the function string_mode. For example, if the input string is “telephone”, the function must return that the most frequent character is “e” and the frequency of “e” is 3. In case of strings where there are multiple characters with the same frequency (for example, “mama”), the program must return the most frequent characters and their frequency (in the “mama” example, the program must return that “m” and “a” are the most frequent characters, and that the frequency is 2). [Hint: you can return multiple outputs from a function. If the variable that stores the most frequent character is called max_char and the frequency associated with this character is called max_frequency, you can write return max_char, max_frequency].

Explanation / Answer

screenShot

---------------------------------------------------------------------------------------------------------------------------

Program

val = 256
def string_mode(string):
    # Create array to keep the count of individual characters
    stringArray= [0]*val
    # variables to get most frequent character and it's count
    max_frequency = -1
    max_char=''
    # Traversing through the string and maintaining the count of each character
    for i in string:
        stringArray[ord(i)]+=1;
    #traversing through the count array to set maximum count and character
    for i in string:
        if max_frequency< stringArray[ord(i)]:
            max_frequency = stringArray[ord(i)]
            max_char=i
    #return value
    return max_char,max_frequency

#string to test
string = "telephone"
#accept return values
[a,b]=string_mode(string)
#print the result
print (" The most frequent character is "+a+" and the frequency of "+a+" is "+str(b))

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote