50.0k views
1 vote
Write a function that displays the character that appears most frequently in the string. If several characters have the same highest frequency, displays the first character with that frequency. Note that you must use dictionary to count the frequency of each letter in the input string. NO credit will be given without using dictionary in your program

1 Answer

6 votes

Answer:

The function is as follows:

def getMode(str):

occurrence = [0] * 256

dict = {}

for i in str:

occurrence[ord(i)]+=1;

dict[i] = occurrence[ord(i)]

highest = max(dict, key=dict.get)

print(highest)

Step-by-step explanation:

This defines the function

def getMode(str):

This initializes the occurrence list to 0

occurrence = [0] * 256

This creates an empty dictionary

dict = {}

This iterates through the input string

for i in str:

This counts the occurrence of each string

occurrence[ord(i)]+=1;

The string and its occurrence are then appended to the dictionary

dict[i] = occurrence[ord(i)]

This gets the key with the highest value (i.e. the mode)

highest = max(dict, key=dict.get)

This prints the key

print(highest)

User John Siracusa
by
6.9k points