0

Hi guys,

I've almost finished my assignment but the last question is kind of a curve ball (for me).

She wants us to create function that accepts a list of words and then returns the longest word in the list. This is what I've come up with:

def longestWord(wordlist):
    i = 0
    x = 0
    while i < len(wordlist):
        if len(wordlist[i]) > x:
            x = wordlist[i]
        i = i + 1
    return x

The problem I have is that when I run it with these a parameters:

y = ["bob", "go", "if", "tarantula", "dodge"]
print a3.longestWord(y)

All i get back is the first word: "bob"

This is new to me and i think the part that says

if len(wordlist[i]) > x

is the problem. Can someone give me an idea where to start looking for the problem? My troubleshooting skills aren't the greatest but this is the first time I'm TOTALLY not sure of where to go.

2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by scru
0

muahhahaha nevermind. I figured it out. should have been len(x)

0

Uhm, just in case your teacher might deduct points for this, instead of initialising x as an int, like:

x = 0

initialise it to an empty string:

x = ""

I think that is what might have confused you in the first place!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.