[Tutor] Finding the shortest word in a list of words

Lie Ryan lie.1296 at gmail.com
Tue Jan 20 14:42:42 CET 2009


On Mon, 19 Jan 2009 19:13:32 -0800, Marc Tompkins wrote:

> 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:

<snip code>

> 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:

Other than overkill, it is wrong. If the shortest "word" is longer than 
maxint it'd give wrong result. You could just simply use the len of the 
first word.

The best solution though, have been answered by Kent Johnson.



More information about the Tutor mailing list