The longest word

Peter Otten __peter__ at web.de
Tue Jul 28 06:14:34 EDT 2009


NiklasRTZ wrote:

> On Jul 28, 5:02 am, Bearophile <bearophileH... at lycos.com> wrote:
>> On Jul 28, 10:26 am, NiklasRTZ <nikla... at gmail.com> wrote:
>>
>> > Newbie hello onwards to the .py manual asks meantime how the longest
>> > word gets determined?
>> > First word, ok
>> > 'a aa aaa aa'[:'a aa aaa aa'.find(' ',1,10)]
>>
>> Your language is not easy to understand, but I think you want to find
>> the longest word in a string.
>> If this is the input string:
>> txt = "a aa aaa aa"
>>
>> There are several ways to do it, I'll show a simple one.
>>
>> You can split it into its parts (not having Python a built-in lazy
>> split yet, you can split it all at once). You can do it with the
>> string split method. It produces a list of the words, more or less
>> (but you may have words like "gone,", you may have to take care of
>> them too, this requires some code.
>>
>> Once you have a list of words, you have to take the longest. A simple
>> way is to replace each word with a tuple that contains the length of
>> the word and the word itself, then pick the tuple with the highest
>> length value. But Python allows you to do such operation in a faster
>> way: you can use the max() function, it has a "key" function that
>> allows you to remap on the fly what you mean by "max". So you just
>> have to give it a function (reference) that given the word spits its
>> length, such function is "len" itself.
>>
>> If you instead want to find the position of the longest word the
>> program gets a little longer. Ask if you need something different.
>>
>> Bye,
>> bearophile
> 
> Thank you. This seems to work:
> sorted("a AAA aa aaaaa  sdfsdfsdfsdf vv".split(' '),lambda a,b: len(a)-
> len(b))[-1]
> 'sdfsdfsdfsdf'

To spell out bearophile's more efficient suggestion:

>>> max("a AAA aa aaaaa  sdfsdfsdfsdf vv".split(), key=len)
'sdfsdfsdfsdf'






More information about the Python-list mailing list