Python Forum

Full Version: Help with string practice
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone,
I'm looking for some help with an exercise I was doing, regarding strings in python.
This program is supposed to find the longest word out of a list of words the user types (i.e. if I type "chicken, dog and cat" the output will be "chicken"), but for the sake of a possibility, if I did type, for example, only "dog and cat", the output will always be dog. Thing is, I want my program to print them both.
Here is the code:

def longest_word(l):
    lenl=[]
    for n in l:
        lenl.append((len(n), n))
    lenl.sort()
    return(lenl[-1][1])
lis=input("Insert some words ").replace(",", " ").replace("and", " ")
lispar=lis.split(" ")
print(longest_word(lispar))
Thanks in advance! ( Oh, and if you find anything I could improve here, furthermore, just let me know, it's very appreciated Tongue )
You have the longest word and you know it's length (len[-1][0]). You need to gather all the words with that length:

def longest_word(l):
    lenl=[]
    for n in l:
        lenl.append((len(n), n))
    lenl.sort(reverse = True)  # Reversing makes the next part easier.
    longest = []
    for length, word in lenl:
        if length == lenl[0][0]:
            longest.append(word)
        else:
            break
    return(list(reversed(longest)))  # Revesing again to put them back in order.
lis=input("Insert some words ").replace(",", " ").replace("and", " ")
lispar=lis.split(" ")
print(longest_word(lispar))
A handy thing when building lists like this is a list comprehension:

output = []
for item in data:
    if condition:
        output.append(function(item))

# is equivalent to

output = [function(item) for item in data if condition]
So we can redo the above code as:

def longest_word(l):
    lenl=[(len(word), word) for word in l]
    lenl.sort(reverse = True)
    longest = [word for length, word in lenl if length == lenl[0][0]]
    return(longest[::-1])  # Another way to revese a list.
lis=input("Insert some words ").replace(",", " ").replace("and", " ")
lispar=lis.split(" ")
print(longest_word(lispar))
Other advice: Avoid single letter variable names. Descriptive, full word names make your code more readable. 'longest_word' is a good name, stick to things like that.
Thank you very much for the explanation! Have a good day :)