Python Forum
Help with string practice - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Help with string practice (/thread-12233.html)



Help with string practice - Hermann_Fegelein - Aug-15-2018

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 )


RE: Help with string practice - ichabod801 - Aug-15-2018

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.


RE: Help with string practice - Hermann_Fegelein - Aug-15-2018

Thank you very much for the explanation! Have a good day :)