[Tutor] Finding the shortest word in a list of words
Marc Tompkins
marc.tompkins at gmail.com
Tue Jan 20 04:13:32 CET 2009
2009/1/19 John Fouhy <john at fouhy.net>
> 2009/1/20 Emad Nawfal (عماد نوفل) <emadnawfal at gmail.com>:
> Of course, this is not necessarily the best answer for your particular
> problem. The problem with sorting is that you have to look at some
> elements more than once. For short lists, it's not a problem, but it
> can slow you down on bigger lists. You could also find the shortest
> element by going through the list, remembering the shortest element
> you've seen so far. This will be quicker if you only want to find the
> single shortest.
>
Here's the first thing that came to mind:
> from sys import maxint
>
> def MinMax(Sentence=""):
> minLen = maxint
> maxLen = 0
>
> for word in Sentence.split():
> if len(word) > maxLen:
> maxWord = word
> maxLen = len(word)
> if len(word) < minLen:
> minWord = word
> minLen = len(word)
> return minLen, minWord, maxLen, maxWord
>
>
> print MinMax("No victim has ever been more repressed and alienated than the
> truth")
>
Using sys.maxint to prime minLen is overkill, of course -
"antidisestablishmentarianism" is only 28 letters long, after all - but it
should be larger than any word you can expect to see.
This doesn't catch ties, though... could do that like so:
for word in Sentence.split():
> if len(word) == minLen:
> minWord.append(word)
> if len(word) == maxLen:
> maxWord.append(word)
> if len(word) > maxLen:
> maxWord = [word]
> maxLen = len(word)
> if len(word) < minLen:
> minWord = [word]
> minLen = len(word)
>
>
--
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090119/b929af6c/attachment.htm>
More information about the Tutor
mailing list