0% found this document useful (0 votes)
14 views

Exp 6

The document describes a function to find and print the letters in a string in decreasing order of frequency. It uses a dictionary to count the frequency of each character and then prints the characters and their frequencies in sorted order.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Exp 6

The document describes a function to find and print the letters in a string in decreasing order of frequency. It uses a dictionary to count the frequency of each character and then prints the characters and their frequencies in sorted order.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Write a function called most_frequent that takes a string and prints the letters in

decreasing order of frequency.

def printChar(arr, Len):

# To store the
occ = {}
for i in range(Len):

if(arr[i] in occ):
occ[arr[i]] = occ[arr[i]] + 1

else:
occ[arr[i]] = 1

# Map's size
size = len(occ)

# While there are elements in the map


while (size > 0):

# Finding the maximum value


# from the map
currentMax = 0
arg_max = 0
for key, value in occ.items():

if (value > currentMax or (value == currentMax and key >


arg_max)):
arg_max = key
currentMax = value

# Print the character


# alongwith its frequency
print(f"{arg_max} - {currentMax}")

# Delete the maximum value


occ.pop(arg_max)
size -= 1

# Driver code
Str = "geeksforgeeks"
Len = len(Str)

printChar(list(Str), Len)

Output
e - 4
s - 2
k - 2
g - 2
r - 1
o - 1
f - 1
--------------------------------------------------------------------------------------------------------------------------------------
def most_frequent(string):
d = dict()
for key in string:
if key not in d:
d[key] = 1
else:
d[key] += 1
return d

print most_frequent('aabbbc')
Returning:

{'a': 2, 'c': 1, 'b': 3}


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

W= input('Please enter a string ')


def most_frequent(string):
d = dict()
for key in string:
if key not in d:
d[key] = 1
else:
d[key] += 1
return d

print (most_frequent(W))
--------------------------------------------------------------------------------------------------------------------------------------

You might also like