I'm using Python 3.4 and am getting an error message " 'wordlist is not defined' " in my program. What am I doing wrong? Please respond with code.
The program is to find the longest word:
def find_longest_word(a):
length = len(a[0])
word = a[0]
for i in wordlist:
word = (i)
length = len(i)
return word, length
def main():
wordlist = input("Enter a list of words seperated by spaces ".split()
word, length = find_longestest_word(wordlist)
print (word, "is",length,"characters long.")
main()
Apart from the problems with your code indentation, your find_longest_word() function doesn't really have any logic in it to find the longest word. Also, you pass it a parameter named a, but you never use a in the function, instead you use wordlist...
The code below does what you want. The len() function in Python is very efficient because all Python container objects store their current length, so it's rarely worth bothering to store length in a separate variable. So my find_longest_word() simply stores the longest word it's encountered so far.
def find_longest_word(wordlist):
longest = ''
for word in wordlist:
if len(word) > len(longest):
longest = word
return longest
def main():
wordlist = input("Enter a list of words separated by spaces: ").split()
word = find_longest_word(wordlist)
print(word, "is" ,len(word), "characters long.")
if __name__ == '__main__':
main()
The line "return word, length" is outside any function. The closest function is "find_longest_word(a)", so if you want it to be a part of that function, you need to indent lines 4-7.
Indentation matters in Python. As the error says, you have the return outside the function. Try:
def find_longest_word(a):
length = len(a[0])
word = a[0]
for i in wordlist:
word = (i)
length = len(i)
return word, length
def main():
wordlist = input("Enter a list of words seperated by spaces ".split()
word, length = find_longestest_word(wordlist)
print (word, "is",length,"characters long.")
main()
In python the indentation is very important. It should be:
def find_longest_word(a):
length = len(a[0])
word = a[0]
for i in wordlist:
word = (i)
length = len(i)
return word, length
But because of the function name, I think the implementation is wrong.
Related
This is the function:
def initials(phrase):
words = phrase.split()
result = ""
for word in words:
result += word[0]
return result.upper()
This is an exercise on my online course. The objective is to return the first initials of a string capitalized. For example, initials ("Universal Serial Bus") should return "USB".
phrase is a str type object.
str objects can have functions applied to them through their methods. split is a function that returns a list containing multiple str objects. This is stored in words
the for word in words takes each element of words and puts it in the variable word for each iteration of the loop.
The += function adds the first letter of word to result by accessing the first character of the str by using the [0] index of word.
Then the upper function is applied to the result.
I hope this clears it up for you.
def initials(phrase):
words = phrase.split()
result = ""
for word in words:
result += word[0]
return result.upper()
This:
Splits the phrase at every space (" "), with phrase.split(). .split() returns a list which is assigned to words
Iterates through the list words and adds the first letter of each word (word[0]) to the result variable.
Returns result converted to uppercase (result.upper())
def initials(phrase):
words = phrase.split()
result = ""
for word in words:
result += word[0].upper()
return result
print(ShortName("Active Teens Taking Initiative To Understand Driving Experiences"))
Should be: ATTITUDE
def initials(phrase):
words =phrase.split()
result=""+""
for word in words:
result += word[0].upper()
return result
print(initials("Universal Serial Bus")) # Should be: USB
print(initials("local area network")) # Should be: LAN
print(initials("Operating system")) # Should be: OS
Here is output:
USB
LAN
OS
This:
Splits the phrase at every space (" "+" ") and concatenate next one first letter,with phrase.split() returns a list which is assigned to words Iterates through the list words and adds the first letter of each word (word[0]) to the result variable.
Returns result converted to uppercase (result.upper())
strong text
def initials(phrase):
words = phrase.split()
result = ""
for word in words:
result += word[0].uppper()
return result
I am trying to get the largest word that contains the letter 'f' through a for loop, through my code I tried to make it as simple as possible with a if and and statement. It is however not working as it returns the largest word but not the one that includes the letter f, why is it not working?
def main():
sentence = "Absence makes the heart grow fonder"
letter = "f"
longest_word = get_longest_word(sentence, letter)
print('"' + longest_word + '" is the longest word containing the letter "'
+ letter + '".')
def get_longest_word(sentence, letter):
words_list = sentence.split()
largest = words_list[0]
my_list = []
for word in words_list:
if letter in word and len(word) > len(largest):
largest = word
return largest
main()
The reason is that you initialise largest to words_list[0], which is 'Absence', the longest word in the sentence.
Therefore, even when 'fonder' is reached, even though the first part of your if passes (it contains an 'f'), the second part about length does not.
Personally, I would just do this:
from operator import itemgetter
def get_longest_word(sentence, letter):
words_with_letter = ((word, len(word)) for word in sentence.split() if letter in word)
return max(words_with_letter, key=itemgetter(1))[0]
This converts the sentence into an iterable of tuples where the first element is the word and the second its length, and where all the words already contain the letter in question.
Then, all we need to do is get the word with the longest length i.e. the highest value in the second position.
Output:
"fonder" is the longest word containing the letter "f".
You can approach this much more easily using the in operator:
for word in word_list:
if 'f' in word:
longest_words.append(word)
longest_word = sorted(longest_words)[0]
Need to find the longest word in a string and print that word.
1.) Ask user to enter sentence separated by spaces.
2.)Find and print the longest word. If two or more words are the same length than 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 when trying to compare the lenghts of words in a sentance. I'm a student who's been using python for 5 weeks.
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'
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 a try/except as suggested by jon clements:
def max_word(splitlist):
try:
return max(splitlist.split(),key=len)
except ValueError:
return " "
You're going in the right direction. Most of your code looks good, you just need to finish the logic to determine which is the longest word. Since this seems like a homework question I don't want to give you the direct answer (even though everyone else has which I think is useless for a student like you), but there are multiple ways to solve this problem.
You're getting the length of each word correctly, but what do you need to compare each length against? Try to say the problem aloud and how you'd personally solve the problem aloud. I think you'll find that your english description translates nicely to a python version.
Another solution that doesn't use an if statement might use the built-in python function max which takes in a list of numbers and returns the max of them. How could you use that?
You can use nlargest from heapq module
import heapq
heapq.nlargest(1, sentence.split(), key=len)
sentence = raw_input("Enter sentence: ")
words = sentence.split(" ")
maxlen = 0
longest_word = ''
for word in words:
if len(word) > maxlen:
maxlen = len(word)
longest_word = word
print(word, maxlen)
The full question is "Write a function find_longest_word() that takes a list of words and
returns the longest word and length of the longest one. You should also write a test function
that will request the users for a list of words and print the longest word and its length."
I wrote this code and it works. I just need to figure out how i can add a function into this code to to what I am told in the question.
def main():
text = input("Please input a list of words to evaluate: ")
longest = 0
for words in text.split():
if len(words) > longest:
longest = len(words)
longest_word = words
print("The longest word is", longest_word, "with length", len(longest_word))
main()
Simply move the logic, into a function, like this
def find_longest_word(text):
for words in text.split():
if len(words) > longest:
longest = len(words)
longest_word = words
return longest_word, len(longest_word)
def main():
input_string = input("Please input a list of words to evaluate: ")
longest_word = find_longest_word(input_string)
print("The longest word is", longest_word, "with length", len(longest_word))
The actual problem, you are trying to solve can be solved like this
def find_longest_word(text):
longest_word = max(text.split(), key = len)
return longest_word, len(longest_word)
Note: Instead of printing the result in the find_longest_word function, we are returning the longest_word from it, so that the function does only what it is supposed to do. Now, as the name suggests, it just finds the longest word.
This exercise with a short codec....
def main():
a = sorted(input("Please input a list of words to evaluate: ").split(), key=len) [-1]
print ("You longe word ", str(a), " have this", str(len(a)), "lenghts")
main()
You do not need longest_word = words, but without your answer, It was not possible to answer this exercise ...., so thanks!
def main ():
text = input("Please input a List of words to evaluate: ")
longest = 0
for words in text.split():
if len(words) > longest:
longest = len(words)
print ("The longest word is", words, "with lenght", longest)
main()
def find_longest_word(words_list):
word_len = []
for n in words_list:
word_len.append((len(n), n))
word_len.sort()
return word_len[-1][1]
print(find_longest_word(["hasta ", "lavista", "baby"]))
this is a python program to read a list of words and return the length of the longest one:
list_words = ["PHP", "Exercises", "Backend"]<br/>
s = [(len(word),word) for word in list_words] <br/>
s.sort() <br/>
print('Longest String in list is ',s[-1][1]) <br/>
numberOfWordsInList = int(input("Enter number of words to be List: "))
def longestWordInList(numberOfWordsInListt):
createdList = [input("Enter any word: ") for i in range(numberOfWordsInList)]
lengthOfItems = [(len(items), items) for items in createdList]
return max(lengthOfItems)
print(longestWordInList(numberOfWordsInList))
I am given a text file that is stored in a list called words_list:
if __name__ = "__main__":
words_file = open('words.txt')
words_list = []
for w in words_file:
w = w.strip().strip('\n')
words_list.append(w)
That's what the list of strings look like (it's a really, really long list of words)
I have to find "all the words" with all of the vowels; so far I have:
def all_vowel(words_list):
count = 0
for w in words_list:
if all_five_vowels(w): # this function just returns true
count = count + 1
if count == 0
print '<None found>'
else
print count
The problem with this is that count adds 1 every time it sees a vowel, whereas I want it to add 1 only if the entire word has all of the vowels.
Simply test if any of your words are a subset of the vowels set:
vowels = set('aeiou')
with open('words.txt') as words_file:
for word in words_file:
word = word.strip()
if vowels.issubset(word):
print word
set.issubset() works on any sequence (including strings):
>>> set('aeiou').issubset('word')
False
>>> set('aeiou').issubset('education')
True
Assuming the word_list variable is an actual list, probably your "all_five_vowels" function is wrong.
This could be an alternative implementation:
def all_five_vowels(word):
vowels = ['a','e','o','i','u']
for letter in word:
if letter in vowels:
vowels.remove(letter)
if len(vowels) == 0:
return True
return False
#Martijn Peters has already posted a solution that is probably the fastest solution in Python. For completeness, here is another good way to solve this in Python:
vowels = set('aeiou')
with open('words.txt') as words_file:
for word in words_file:
word = word.strip()
if all(ch in vowels for ch in word):
print word
This uses the built-in function all() with a generator expression, and it's a handy pattern to learn. This reads as "if all the characters in the word are vowels, print the word." Python also has any() which could be used for checks like "if any character in the word is a vowel, print the word".
More discussion of any() and all() here: "exists" keyword in Python?