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.

Recommended Answers

All 2 Replies

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

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!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.