Comparing word lengths in strings
You need to find the longest word in the string and type that word. 1.) Ask the user to enter a sentence separated by spaces. 2.) Find and type the longest word. If two or more words are the same length then print the first word.
this is what i have so far
def maxword(splitlist): #sorry, still trying to understand loops
for word in splitlist:
length = len(word)
if ??????
wordlist = input("Enter a sentence: ")
splitlist = wordlist.split()
maxword(splitlist)
I'm hitting a wall trying to compare the length of the words in a mailing list. I am a student who has been using python for 5 weeks.
source to share
def longestWord(sentence):
longest = 0 # Keep track of the longest length
word = '' # And the word that corresponds to that length
for i in sentence.split():
if len(i) > longest:
word = i
longest = len(i)
return word
>>> s = 'this is a test sentence with some words'
>>> longestWord(s)
'sentence'
source to share
You are going in the right direction. Most of your code looks good, you just need to complete the logic to determine which is the longest word. Since this seems like a homemade question, I don't want to give you a straight answer (although everyone else has, which I think is useless for a student like you), but there are several ways to solve this problem.
You are correctly determining the length of each word, but what do you need to compare each length? Try saying the problem out loud and how you personally solve the problem out loud. I think you will find that your English description translates nicely into the python version.
Another solution not using the operator if
could use the built-in python function max
that takes a list of numbers and returns the maximum number of them. How could you use this?
source to share
You can use max with a key:
def max_word(splitlist):
return max(splitlist.split(),key=len) if splitlist.strip() else "" # python 2
def max_word(splitlist):
return max(splitlist.split()," ",key=len) # python 3
Or use try / except as suggested by jon clements:
def max_word(splitlist):
try:
return max(splitlist.split(),key=len)
except ValueError:
return " "
source to share