tags:

views:

556

answers:

4

how determine the longest word? First word, ok

'a aa aaa aa'[:'a aa aaa aa'.find(' ',1,10)]

'a'

rfind is another subset

'a aa aaa aa'[:'a aa aaa aa'.rfind(' ',1,10)]

'a aa aaa'

One row should be able. It's a direct word 'a aa aaa...' and can be a variable, no problem it occurs twice still naturally easier if also occured just once. I shan't need a function, class, just one row. Sincere thanks & regards

+15  A: 

If I understand your question correctly:

>>> s = "a aa aaa aa"
>>> max(s.split(), key=len)
'aaa'

split() splits the string into words (seperated by whitespace); max() finds the largest element using the builtin len() function, i.e. the string length, as the key to find out what "largest" means.

balpha
+1 really elegant code (at least for a Java developer)
dfa
+1 excellent solution
ThomasH
A: 

All normal questions here are difficult and programming too. It works with gae. What do you think:

    'input':sorted(List.all().filter('published =',True).order('-modified').get().title.split(' '),lambda a,b: len(a)-len(b))[-1],

Pure python

>>> sorted("a AAA aa aaaaa  sdfsdfsdfsdf vv".split(' '),lambda a,b: len(a)-len(b))[-1]

'sdfsdfsdfsdf'

LarsOn
A: 
sorted("a AAA aa aaaaa sdfsdfsdfsdf vv".split(' '),key=len)[-1]
LarsOn
+2  A: 

Here is one from the category "How difficult can you make it", also violating the requirement that there should be no own class involved:

class C(object): pass
o = C()
o.i = 0
ss = 'a aa aaa aa'.split()
([setattr(o,'i',x) for x in range(len(ss)) if len(ss[x]) > len(ss[o.i])], ss[o.i])[1]

The interesting bit is that you use an object member to maintain state while the list is being computed in the comprehension, eventually discarding the list and only using the side-effect.

But please do use one of the max() solutions above :-) .

ThomasH
Ah, even better: o.i = ''; ([setattr(o,'i',x) for x in s.split() if len(x) > len(o.i)], o.i)[1]
ThomasH