Write a function longestWord(WORDS) in Python, that takes the dictionary, WORDS as an argument and returns the longest word (in lowercase) in the dictionary. If there are more than one words with the same length, return the first one in alphabetical order.
For example, Consider the following dictionary
WORDS={1:"Apple",2:"Orange",3:"Banana",4:"Grape",5:"Kiwi"}
The output should be:
banana
Answer:
Answer by student
Detailed answer by teachoo
-lock-
- The question asks us to write a function that takes a dictionary as an argument and returns the longest word in the dictionary. If there are more than one words with the same length, we have to return the first one in alphabetical order.
- To solve this problem, we can use the following steps:
- Define a function named longestWord that takes a parameter named WORDS , which is a dictionary of words.
- Initialize an empty string variable named longest to store the longest word.
- Loop through the values of the dictionary using a for loop. We can use the .values() method to get a list of values from the dictionary.
- Convert each value (word) to lowercase using the .lower() method . This is because we want to compare and return the words in lowercase.
- Compare the length of each word with the length of the longest word using the len() function and an if statement. If the length of the current word is greater than the length of the longest word, we update the longest variable with the current word.
- If the length of the current word is equal to the length of the longest word, we have to compare them in alphabetical order using another if statement. We can use the < operator to check if one string comes before another string in alphabetical order. If the current word comes before the longest word, we update the longest variable with the current word.
- After looping through all the values, we return the longest variable as the output of the function using a return statement.
- Here is how our code would look like:
-endlock-