Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Longest word in a list!

Write a function called longest which will take a string of space separated words and will return the longest one.

For example: longest("So Super Fly") => "Super"

1 Answer

I am sure Nelson that you gave it a fair try but please do share your code or otherwise mention how much help you need regarding the matter. As per the understanding of community forums, it is suggested to not feed the code.

Here i'll share approach and the final solution as well.

1> If you haven't tried, then this is how you can proceed.

take the string as function argument;

split the string using split() function and split would return the list of all the words separated by space.

traverse through the list and find out the string with maximum length. You will need to store the information in some variable.

2> Here is the final solution.

.

.

def longest(string):
    tokens = string.split();
    max_length = 0;
    max_word="";
    for token in tokens:
        if len(token)>max_length:
            max_length = len(token)
            max_word = token
    return max_word;

Thanks so much, it just worked well.