This question already has answers here:
How to find the longest word with python?
(5 answers)
Closed 7 years ago.
I a new to python and am stuck on this one exercise. I am supposed to enter a sentence and find the longest word. If there are two or more words that have the same longest length, then it is to return the first word. This is what I have so far:
def find_longest_word(word_list):
longest_word = ''
for word in word_list:
print(word, len(word))
words = input('Please enter a few words')
word_list = words.split()
find_longest_word(word_list)
But I do not know how to compare the lists and return the first/longest word.
Use max python built-in function, using as key parameter the len function. It would iterate over word_list applying len function and then returning the longest one.
def find_longest_word(word_list):
longest_word = max(word_list, key=len)
return longest_word
You shouldn't print out the length of each word. Instead, compare the length of the current word and the length of longest_word. If word is longer, you update longest_word to word. When you have been through all words, the longest world will be stored in longest_word.
Then you can print or return it.
def find_longest_word(word_list):
longest_word = ''
for word in word_list:
if len(word) > len(longest_word)
longest_word = word
print longest_word
edit:
levi's answer is much more elegant, this is a solution with a simple for loop, and is somewhat close to the one you tried to make yourself.
Compare each word to the longest one yet, starting with the length of 0. If the word is longer than the longest yet, update the word and the longest_size. Should look similar to this:
def find_longest_word(word_list):
longest_word = ''
longest_size = 0
for word in word_list:
if len(word) > longest_size
longest_word = word
longest_size = len(word)
return longest_word
words = input('Please enter a few words')
word_list = words.split()
find_longest_word(word_list)
Related
Write a function longest_word that asks the user for words and returns the longest word entered by the user. It should stop when the user hits return without typing a word. If multiple words have the same maximum length, return the first word entered by the user. If the user quits before entering any words, return “No words were entered”. This function should use a searching loop. (Hint: remember that the len function returns the length of a string.)
def longest_word():
word = input("enter a word")
if word == "":
return "No words were entered"
max = 0
while len(word) > max :
max = len(word)
new_word = input("enter a word")
if len(new_word) <= len(word):
print(word)
else:
print(new_word)
longest_word()
I understand that I need to iterate the while loop until the user enters without typing any words, but I do not know how to write the corresponding code.
The logic of your code had some flaws.
You need to run the while loop until the input is "" or an empty string and the len(word)>max needs to be inside an if statement. This is because the input value decides whether to break the loop or continue it, the difference in lengths just determines the result.
The returned word should be the longest one(only). But the block:
if len(new_word) <= len(word):
print(word)
else:
print(new_word)
Prints every entered word that is longer than the previous one.
3. You need to change the value of the previous word or the longest word every time a longer word is entered so that it is updated, not just the value of the length.
The code might look like:
def longest_word():
word = input("enter a word")
if word == "":
return "No words were entered"
max = 0 # This variable is not exactly required
longest = word # this variable stores the longest word(currently)
new_word = None # This assignment is for checking for empty strings
while new_word != "" :
max = len(word)
new_word = input("enter a word")
if len(new_word) >= len(longest): # If the entered word is longer, change
# value of the longest word
longest = new_word
print(longest) # Print the longest word.
longest_word()
This is not necessary but avoid naming variables the same as keywords as it often causes a confusion
Some key points of what this function needs to do:
It needs to return the longest word, not print it.
It needs to keep track of the longest word seen so far (so it can return it when it's done). Keeping track of the length of the longest word is not sufficient.
Here's how I might write it:
def longest_word():
longest = ""
while True:
word = input("enter a word")
if not word:
return longest or "No words were entered"
if len(word) > len(longest):
longest = word
Note that the return line immediately ends the loop once no word is entered, and the or statement handles the case where nothing was entered prior to that point.
The remaining if statement ensures that longest is the longest word seen so far.
I am trying to write python code that takes words from an array and makes a new array that includes all of the longest words of the previous array. I can't find where the problem is, but whenever I run this, it just eats a ton of RAM but doesn't work (it should print the words Good and Cool). Does anyone see the problem?
words = ["Good", "Bad", "Cool"]
def longest_word():
longest = [""]
for word in words:
for word2 in longest:
if len(word) > len(word2):
longest.clear()
longest.append(word)
elif len(word) == len(word2):
longest.append(word)
print(str(longest_word))
longest_word()
You could do this in a list comprehension using the max function like this:
words = ["Good", "Bad", "Cool"]
max_length = len(max(words,key=len))
longest = [word for word in words if len(word) == max_length]
The max function will return the string with the most characters because of the key=len argument, and then you compare the length of each word in your list to the length of the returned string from max. If the lengths match then it adds the word to the longest list.
Edit: Changed my answer to reflect #NathanielFord's suggestion
While I wouldn't go about it this way, you're pretty close with a few simplifications:
words = ["Good", "Bad", "Cool"]
def longest_word():
longest = [] # Don't add an empty word here
l = len(words[0]) # Remember the length of the first word
for word in words:
if len(word) > l: # If the next word is longer than the longest length found so far...
longest = [] # Reset your list
longest.append(word) # Add the word
l = len(word) # Remember the new longest length
elif len(word) == l:
longest.append(word)
print(longest)
longest_word()
There are two reasons not to iterate over the longest list. The first is that you're actively modifying that list - if you clear it in the middle of doing so it will lead to strange results. Secondly, it's much more computationally expensive - you might get O(n^2) time in the worst case. The only info you need is the length so far of the longest word, so remember that and update it instead of trying to recheck each element of your longest list. (After all, you know all those elements have to equal each other!)
You could just loop through once getting the length of each word and saving it to a longestWord variable if it's greater. Then loop through a second time to add it to the array if it's the same length as the longestWord variable.
So I'm trying to create a program that takes sentences and makes words of length 5 or longer reverse itself. At the moment it is only flipping the last word that meets the condition and I don't know why.
userInput = "Hello this is a test sentence"
wordList = userInput.split()
for i in wordList:
if len(i) >= 5:
reversedWord = i[::-1]
print(reversedWord)
reversedSentence = userInput.replace(i, reversedWord)
print(reversedSentence)
Instead of outputing "olleH this is a test ecnetnes" it outputs "Hello this is a test ecnetnes"
You keep replacing the original userInput
reversedSentence = userInput
for i in wordList:
if len(i) >= 5:
reversedWord = i[::-1]
print(reversedWord)
reversedSentence = reversedSentence.replace(i, reversedWord)
You need to keep updating the reversedSentence variable instead.
The actual bug in your code has already been stated, I just want to add some feedback regarding the style:
You are performing the following steps:
split the input into words
find words that meet your requirement (len(word) > 5)
change the original string for each of those
This is rather unconventional and a bit unintuitive (it also has bad performance, since it manipulates your original string multiple times). I recommend the following algorithm instead:
split the input into words
reverse the words meeting your requirement inside that list
join the list into a sentence again to get your string
Example implementation:
user_input = "Hello this is a test sentence"
processed_words = []
for word in user_input.split():
if len(word) >= 5:
word = word[::-1]
processed_words.append(word)
reversed_sentence = ' '.join(processed_words)
print(reversed_sentence)
Taking this idea a bit further by using a generator expression, it might look like this:
user_input = "Hello this is a test sentence"
reversed_sentence = ' '.join(
word[::-1] if len(word) >= 5 else word
for word in user_input.split())
print(reversed_sentence)
Again, having trouble wrapping my head around an assignment. I have a list which is created by user input, and I want to find the longest word from the list. I have been able to get the list but my output is incorrect and I am having an issue trying to compare the words from the list. I realize this is a duplicate question in a couple of other threads but after trying those suggestions I am still having an issue. This is what I have thus far, and thank you in advance:
def find_longest_word(wordList):
longest=''
previous=''
for word in wordList:
if len(word)>len(longest):
longest=word
print(longest)
else:
previous=word
print(previous)
print('Please enter a few words and I will find the longest word:','\n')
words = input()
print('\n')
wordList = words.split()
print('The list of words entered is:','\n')
print(wordList)
find_longest_word(wordList)
Have you tried the following?
def find_longest_word(wordList):
return max(wordList, key=len)
This simple line finds the maximum value of the wordList, comparing the values in the list by their length.
Let's define a list of words as such:
wordList = ['word', 'longestWord', 'shorter']
You can find the index of the longest word with
maxIndex = max(enumerate(map(lambda x: len(x), wordList)), key=(lambda x: x[1]))
and finally see the longest word with:
wordList[maxIndex[0]]
I would like to compare the input letters(dictionary) with the list(textfile with words) and print the words matching the inputed letters. What have I done wrong?(I know i only have a print YES or NO-function if it finds a matching word at the moment. What's the best way to create this function by the way?).
def ordlista(list):
fil = open("ord.txt", "r")
words = fil.readlines()
list = []
for w in words:
w = w.strip()
list.append(w)
return list
chars = {}
word = raw_input("Write 9 letters: ")
for w in word:
w = w.lower()
if w not in chars:
chars[w] = 1
else:
chars[w] += 1
if chars.keys() in ordlista(list):
print "YES"
else:
print "NO"
chars.keys() is a list, so
chars.keys() in ordlista(list):
will never be True. What you want is match the letter counts against each word in your list. So I'd suggest
charsum = sum(chars.values())
for word in wordlist:
if len(word) == charsum and all([(word.count(c) == chars[c]) for c in chars]):
print "YES for word '%s'" % word
EDIT: If you want those words to match which have at least the letter counts (i.e. a word with 3 a's will match an input of two a's), then you'll have to change the == to a >=.
EDIT2: Since you want exact matches, the easiest solution would be to count the number of chars and make sure the word has that length.
You are checking for the presence of the entire list of keys in your character list, rather than checking for each key individually. You must iterate over your keys individually, and then check for their presence.
for k in chars:
if k in ordlista(list):
print "YES"
else:
print "NO"
If you want to print the words which consist solely of the letters in your character list, you may use the following approach.
for word in ordlista(list):
if not filter(lambda char: char not in chars, word):
print word
Use sets:
chars = set(raw_input("Write 9 letters: "))
for word in ordlista(None):
if(set(word) == chars):
print "YES for '%s'" % word
BTW, the argument list to ordlista is unnecessary, as it is not used. I would also advise against using the name list in general, because it hides the built-in <type 'list'>
Update: I have read your comment on jellybean's post. If every letter can only be used once, you can obviously not use sets!