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

Emad Nawfal (عماد نوفل) emadnawfal at gmail.com
Tue Jan 20 03:47:44 CET 2009


2009/1/19 John Fouhy <john at fouhy.net>

> 2009/1/20 Emad Nawfal (عماد نوفل) <emadnawfal at gmail.com>:
> > Hello tutors,
> > I need to find the shortest / longest word(s) in a sequence of words.
> I've
> > done this and it works, but I'm wondering whether this is a good way:
> >>>> words = "man woman children he".split()
> >>>> words
> > ['man', 'woman', 'children', 'he']
> >>>> lens = [len(word) for word in words]
> >>>> lens
> > [3, 5, 8, 2]
> >>>> for word in words:
> > ...     if len(word) == min(lens): print word
> > ...
> > he
>
> Hi Emad,
>
> You can use the decorate-sort-undecorate idiom to make this technique
> a bit nicer.
>
> "decorate" means "add information to the things in the list":
>
> >>> words_and_lengths = [(len(w), w) for w in words]
> >>> words_and_lengths
> [(3, 'man'), (5, 'woman'), (8, 'children'), (2, 'he')]
>
> Now I can sort it and get the shortest element easily:
>
> >>> words_and_lengths.sort()
> >>> words_and_lengths[0]
> (2, 'he')
>
> Or I can undecorate:
>
> >>> words2 = [w[1] for w in words_and_lengths]
> >>> words2
> ['he', 'man', 'woman', 'children']
>
> Python 2.5+ provides another way of doing this, using the key=
> argument to sort():
>
> >>> words
> ['man', 'woman', 'children', 'he']
> >>> words.sort(key=len)
> >>> words
> ['he', 'man', 'woman', 'children']
>
> This essentially does the decorate-sort-undecorate in one step, where
> len is the function we used to do the decoration.
>
> 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.
>
> --
> John.
>

Thanks John for this. Although the decorate-sort-undecorate idiom looks so
natural to me now, I don't think I would have found it on my own. I have
that deja vu effect towards it.
Thanks again.

-- 
لا أعرف مظلوما تواطأ الناس علي هضمه ولا زهدوا في إنصافه كالحقيقة.....محمد
الغزالي
"No victim has ever been more repressed and alienated than the truth"

Emad Soliman Nawfal
Indiana University, Bloomington
http://emnawfal.googlepages.com
--------------------------------------------------------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090119/c4297118/attachment.htm>


More information about the Tutor mailing list