Frage

Hi, I'm trying to make an python program that will return the length of the longest word in a list but it does not work so well for me.

here is the code:

def find_longest_word():
   list1 = ['a','aa','aaa','aaaa','aaaaa','aaaaaa','aaaaaaa','aaaaaaaa',]
   max1 = ''
   for x in range (0, len(list1)):
      if (len(max1) < len(list1[x]) ):
          max1 = list1[x]
   return max1    


def main():
    m = find_longest_word()
    print len(m)
War es hilfreich?

Lösung

Actually, your problem is quite simple: you forgot to call the main function at the end of your script:

main()

When you do, it prints 8, just like it should.


However, you can accomplish this task a lot easier if you use max and its key function:

>>> list1 = ['a','aa','aaa','aaaa','aaaaa','aaaaaa','aaaaaaa','aaaaaaaa',]
>>> max(list1, key=len)
'aaaaaaaa'
>>> len(max(list1, key=len))
8
>>>

Edit:

While my above solution works fine, I want to offer an even shorter one I just thought of:

>>> list1 = ['a','aa','aaa','aaaa','aaaaa','aaaaaa','aaaaaaa','aaaaaaaa',]
>>> max(map(len, list1))
8
>>>

Instead of a key function, this solution uses map.

Andere Tipps

This should work

mx=0
for word in list1:
    if len(word)>mx:
        mx=len(word)
#now max will contain the length of longest word

Edit: This might not be the ideal answer, but the intention was to give code which is similar to the code in question.

def find_longest_word():
    list1 = ['a','aa','aaa','aaaa','aaaaa','aaaaaa','aaaaaaa','aaaaaaaa',]  # this should be a parameter
    max1 = ''
    for x in range (0, len(list1)):  # you don't have to include 0 in this
        if (len(max1) < len(list1[x]) ): 
            max1 = list1[x]
    return max1    


def main():
    m = find_longest_word()
    print len(m)

Your indentation was wrong, although that could be formatting from pasting it here. A simpler way that has the same structure as you function:

def find_longest_word(lst):
    max1 = ''
    for x in lst:
        if (len(x) > len(max1)): 
            max1 = x
    return max1    


def main():
    m = find_longest_word()
    print len(m)

with a sorted reverse you can get longest string too

sorted(list1,key=len,reverse=True)[0]
'aaaaaaaa'

Take a look at this:

'''Write a function find_longest_word() that takes a list of words and returns the length of the longest one.'''

a = ['mamao', 'abacate', 'pera', 'goiaba', 'uva', 'abacaxi', 'laranja', 'maca']

def find_longest_word(a):

    d = []
    for c in a:
        d.append(len(c))
        e = max(d)  #Try "min" :D
    for b in a:
        if len(b) == e:
            print "Length is %i for %s" %(len(b), b)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top