+ 3

Someone know more efficient way to find longest word ?

txt = input().split() length = {} x = [] for word in txt: length[len(word)] = word x.append(len(word)) print(length[max(x)]) Help me to shorten this code😭😭

2nd Jan 2023, 7:15 AM
Parveen
Parveen - avatar
5 Antworten
+ 6
txt = input().split() longest_word = max(txt, key=len) Note that the key=len specifies that we must obtain the word depending on its length
2nd Jan 2023, 8:19 AM
Abdelrahman Tlayjeh
+ 6
Jayakrishna🇮🇳 , your sample code does not return the longest word as requested. input of "aaaa xx" returns "xx". for using max() with strings the result will be calculated lexicographically. so a string that starts with "x" is greater than a string that starts with "a". for getting the longest word: see the sample of Abdelrahman Tlayjeh
2nd Jan 2023, 4:52 PM
Lothar
Lothar - avatar
+ 4
Python has already a pre defined function for same purpose implementation: print( max(input().split() ) ) edit: # print(max( txt, key=len) )
2nd Jan 2023, 8:45 AM
Jayakrishna 🇮🇳
+ 3
Lothar I seen it actually largest word. Not longest. And for same length string like above both approaches ["ab", "ad", "ac" ] Op approach returns "ac" And @Abdelrahman approach returns "ab" . It's fine for longest. But largest is actually "ad". I only tested on this case. So waiting for response, it it also need largest. Or just need longest is enough. Yes. I should mention it along.
2nd Jan 2023, 5:03 PM
Jayakrishna 🇮🇳
+ 2
print(max(input().split(),key=len)) this way you apply the max() function based on the length of the word with key=len
4th Jan 2023, 7:07 AM
ElChapo