Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the shortest word in a string

Tags:

python

I'm new to coding and I'm working on a question that asks to find the shortest word within a sentence. I'm confused what the difference between:

def find_short(s):
    for x in s.split():
        return min(len(x)) 

and

def find_short(s):
    return min(len(x) for x in s.split())

is, because the former gives me an error and the latter seems to work fine. Are they not virtually the same thing?

like image 646
Andrew OZEKI Avatar asked Jul 12 '18 20:07

Andrew OZEKI


1 Answers

Are they not virtually the same thing?

No, they are not the same thing. If s equals "hello world", in the first iteration, x would be "hello". And there are two things wrong here:

  • You are trying to return in the very first iteration rather than going over all the elements (words) to find out what's the shortest.
  • min(len(x)) is like saying min(5) which is not only an bad parameter to pass to min(..) but also doesn't make sense. You'd want to pass a list of elements from which min will calculate the minimum.

The second approach is actually correct. See this answer of mine to get an idea of how to interpret it. In short, you are calculating length of every word, putting that into a list (actually a generator), and then asking min to run its minimum computation on it.

There's an easier approach to see why your second expression works. Try printing the result of the following:

print([len(x) for x in s.split()])
like image 189
UltraInstinct Avatar answered Oct 07 '22 12:10

UltraInstinct