Reputation: 23
Assume we have been provided with a string.
s="This is my statement"
We have to get sentence as an output and this needs to be solved using list comprehension concept.
I have tried the code below and it gives me an empty list.
longest_word=[i for i in s.split() if len(i) == max(s)]
Looking for some valid solution/suggestions for this problem.
Upvotes: 1
Views: 297
Reputation: 75635
The error in your code is in the max(s)
expression. The max()
when used this way, returns the character with the highest ASCII value in the string s
and not the length of the longest word as you incorrectly assumed. So when you compare len(i) == max(s)
, you're comparing the length of the current word i
to a character from s
which makes little sense, because a character (which is essentially a string of length 1) and the length of a word (which will be greater than 1 for any word other than a single character) will never be equal, the comparison will always evaluate to False
and that's why you get empty list.
To find the longest word(s) in the string s
can be constructed using the max()
a key
argument where we do pass len
function to be used to compare lengths, along with list comprehension to handle multiple words of the same maximum length:
longest_word_length = max(len(word) for word in s.split())
longest_word = [word for word in s.split() if len(word) == longest_word_length]
And when implemented, your test case would then produce:
$ python test.py
['statement']
Upvotes: 0
Reputation: 13501
I would go with something like
[k:=w for i,w in enumerate(s.split()) if i==0 or len(w)>len(k)][-1]
Not sure. This kind of exercise, that are more a programmer version of taboo game have rules. May be I am not authorized to use :=
. Maybe I was authorized to use more than one line...
Compared to your attempt, it has the advantage of doing one pass. Yours (as corrected by Marcin Orlowski) does two. One (implicit) in the max
function to find the biggest word. Then, another, the list comprehension, to select a word that match that length.
Performance-wise it probably doesn't matter much (the max
function is quite fast, since it is a native function, probably coded in C. So it doesn't cost much to call it before the rather slow for
of the comprehension list).
But, since is obviously a sort of game/challenge/exercise, it may matter to whoever will judge it that the algorithm require 2 passes when only one is really needed.
Upvotes: 0