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

The following code must be written in python: Write a program that reads a seque

ID: 3716498 • Letter: T

Question

The following code must be written in python:

Write a program that reads a sequence of words and prints every word whose frequency is equal to its length. You can assume that there will always be a word that meets this condition. If more than one word have this condition, you must print first the most frequent one. If two or more words with equal frequencies meet this condition, print them from the smallest to the largest in alphabetical order.

Sample Input: lee john lee peter john lee john john

Sample Output: john lee

Note: Your code should be able to convert the sample input into the sample output. However, this is not enough to pass the challenge, because the code will be run on multiple test cases. Therefore, your code must solve this problem statement.

Explanation / Answer

def frequencies(str): words = {} #dictionary res = "" #resultant string list1 = str.split(" ") #split string into list using spaces for eachWord in list1: #iterate list if eachWord not in words: #if word is not found in dictionary words[eachWord] = 1 #set its value as 1 else: words[eachWord] += 1 #if word is found in dictionary, then increment its value by 1 for key,value in words.items(): #iterate dictionary items if len(key) == value: #if length of the key is equals to its value res = key + " " + res #then append the key to the resultant string return res #return result if __name__ == '__main__': print(frequencies("lee john lee peter john lee john john"))

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