[Tutor] list comprehensions
Sean 'Shaleh' Perry
shalehperry@attbi.com
Tue, 20 Aug 2002 20:50:04 -0700
On Tuesday 20 August 2002 08:29 pm, Tim Wilson wrote:
> Hi everyone,
>
> I'm wondering if it's possible to implement the following function usin=
g
> list comprehensions. It's not really a speed issue because it runs in a
> split second using the built-in dictionary on my Linux box.
>
> -Tim
>
> def filterLongest(words):
> """
> Filter a list of words for all words that have a length equal to th=
e
> longest word in the list.
>
> Argument:
> words -- List of words to filter
>
> """
> l =3D []
> maxLength =3D 0
> for word in words:
> wordLength =3D len(word)
> if wordLength =3D=3D maxLength:
> l.append(word)
> elif wordLength > maxLength:
> l =3D [word]
> maxLength =3D wordLength
> return l
this code actual has a fairly big bug.
['a', 'bb', 'ccc', 'dddd', 'eeeee', ...]
given that list each item will end up in the return. You really need to =
loop=20
twice. Once to find the longest word then again to find those that are a=
t=20
least as big. Or did I misunderstand your comment? For instance given m=
y=20
example list above the return list would simply be:
['z' * 26]