+ 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šš
5 Answers
+ 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
+ 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
+ 4
Python has already a pre defined function for same purpose implementation:
print( max(input().split() ) )
edit: # print(max( txt, key=len) )
+ 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.
+ 2
print(max(input().split(),key=len))
this way you apply the max() function based on the length of the word with key=len