0

How can I find the longest word , and print it in python?

Given a text as input, find and output the longest word. Sample Input this is an awesome text Sample Output awesome

6th Oct 2022, 4:46 AM
Iamno0v
Iamno0v - avatar
4 Answers
+ 2
# Function to print the longest # word in given sentence def largestWord(s): # Sort the words in increasing # order of their lengths s = sorted(s, key = len) # Print last word print(s[-1]) # Driver Code if __name__ == "__main__": # Given string s = "this is an awesome text" # Split the string into words l = list(s.split(" ")) largestWord(l)
6th Oct 2022, 5:18 AM
Vishal G
Vishal G - avatar
+ 2
Vishal G Nice, but what if there are two words with the same length?
6th Oct 2022, 7:09 AM
Per Bratthammar
Per Bratthammar - avatar
+ 1
1) Split the string with the text to a list with the texts words as elements, here called txt (lst = txt.split()). 2) Find a way to get the max length for the words in the list (maxlength = max(map(len, lst))). 3) Find way to pick out all the words whos length is equal to the max length (res = [wd for wd in lst if len(wd) == maxlenth]). 4) print the result (print(res)).
7th Oct 2022, 5:10 AM
Per Bratthammar
Per Bratthammar - avatar
0
@ Per Bratthammar Whats the solution?
6th Oct 2022, 2:50 PM
JAbAR
JAbAR - avatar