I'm doing a question on grok learning, it asks for this:
You are learning a new language, and are having a competition to see how many unique words you know in it to test your vocabulary learning.
Write a program where you can enter one word at a time, and be told how many unique words you have entered. You should not count duplicates. The program should stop asking for more words when you enter a blank line.
For example:
Word: Chat
Word: Chien
Word: Chat
Word: Escargot
Word:
You know 3 unique word(s)!
and
Word: Katze
Word: Hund
Word: Maus
Word: Papagei
Word: Schlange
Word:
You know 5 unique word(s)!
and
Word: Salam
Word:
You know 1 unique word(s)!
I cannot get it to work when there are multiple duplicates, here is my code:
word = input("Word: ")
l = []
l.append(word)
words = 1
while word != "":
if word in l:
word = input("Word: ")
else:
words = 1 + words
word = input("Word: ")
print("You know " + str(words) , "unique word(s)!" )
Using a set this problem can be solved easily:
l = set()
while True:
new_word = input("Word:")
if new_word=="":
break
l.add(new_word)
print("You know " + str(len(l)) , "unique word(s)!" )
This is a good example for the power of the Python standard library. Usually if you have a problem there already is a good solution in it.
There is also a way where you do not necessarily have to use the set() function. But it is still best if you learn about the set() function anyway.
Here's the code that doesn't need a set() function, but still works fine:
words = []
word = input('Word: ')
while word != '':
if word not in words:
words.append(word)
word = input('Word: ')
print('You know', len(words), 'unique word(s)!')
Related
This question already has answers here:
Get unique values from a list in python [duplicate]
(30 answers)
Closed 2 years ago.
My question is to ask user input a world at a time and see how many unique world the user know (duplicate word wont count)
e.g.
Word: Chat
Word: Chien
Word: Chat
Word: Escargot
Word:
You know 3 unique word(s)!
below is what I have now:
count = 0
listword = []
word = input("Word: ")
while word != "":
for i in listword:
if i != word:
listword.append(word)
count += 1
word = input("Word: ")
print("You know "+count+"unique word(s)!")
however the output is like this:
Word: hello
Word: hi
Word: hat
Word:
You know 0 unique word(s)!
How can I adjust my code and why is count still =0?
The problem is that listword is initially empty, and nothing ever gets added unless the entered word doesn't match a word already in listword. What you really want to do is to add the word if it isn't found in listword.
You could do that with a list, but a set would be more efficient:
listword = set()
word = input("Word: ")
while word.strip() != "":
if word not in listword:
listword.add(word)
word = input("Word: ")
print("You know", len(listword), "unique word(s)!")
I would suggest using collections.Counter. This provides a simple an pythonic way to calculate total counts and is provided in the standard lib.
You could use it like this:
from collections import Counter
total_counts = Counter()
word = input("Word: ")
while word:
total_counts.update([word])
word = input("Word: ")
print("You know {:d} unique word(s)!".format(len(total_counts)))
Editing your code you can just do:
listword = []
word = input("Word: ")
while word: # empty strings are equal to false as a boolean, and anything in them is equal to true
if word not in listword:
listword.append(word)
word = input("Word: ")
print("You know ",len(listword),"unique word(s)!")
Although I would look into a more pythonic way of doing this if I were you.
Since at the start you declare an empty list:
listword = []
And only append items to it inside this loop:
for i in listword:
You'll never enter this loop, because the list will always be empty, thus you'll never cycle through count += 1.
So you should add another check to see if list is empty:
while word != "":
if len(listword) == 0:
listword.append(word)
count+=1
for i in listword:
if i != word:
#...
This code is same as yours with slight modification.
count = 0
listword = []
word = input("Word: ")
while word != "":
found= False
for i in listword:
if i == word:
found= True
if not found:
listword.append(word)
word = input("Word: ")
print("You know "+str(len(listword))+" unique word(s)!")
The task that I am doing is to develop a program that identifies individual words in a sentence, stores these in a list and replaces each word in the original sentence with the position of that word in the list.
sentencelist=[] #variable list for the sentences
word=[] #variable list for the words
positions=[]
words= open("words.txt","w")
position= open("position.txt","w")
question=input("Do you want to enter a sentence? Answers are Y or N.").upper()
if question=="Y":
sentence=input("Please enter a sentance").upper() #sets to uppercase so it's easier to read
sentencetext=sentence.isalpha or sentence.isspace()
while sentencetext==False: #if letters have not been entered
print("Only letters are allowed") #error message
sentence=input("Please enter a sentence").upper() #asks the question again
sentencetext=sentence.isalpha #checks if letters have been entered this time
word = sentence.split(' ')
for (i, check) in enumerate(word): #orders the words
print(sentence)
word = input("What word are you looking for?").upper() #asks what word they want
if (check == word):
positionofword=print("your word is in this position:", i+1)
positionofword=str(positionofword)
else:
print("this didn't work") #print error message
elif question=="N":
print("The program will now close")
else:
print("you did not enter one of the prescribed letters")
words.write(word + " ")
position.write(positionofword + " ")
The problem for me is that I am stuck in the loop of:
word = input("What word are you looking for?").upper() #asks what word they want
if (check == word):
positionofword=print("your word is in this position:", i+1)
positionofword=str(positionofword)
else:
print("this didn't work") #print error message
Which therefore means that I cannot get the words into the file. I have tried to use break, but that did not work out for me because I could not get the words into the file.
I'm new to this site, but I've been stalking for quite a while. Hopefully this is right, I'm open to hearing criticism if I've worded this wrong.
Your logic in the for loop is incorrect - rather than asking once what the word the user wants to find, you ask that for each word in the sentence, and only match if they enter the word they want when that is the current word being checked. You are also printing the sentence once for each word in the sentence. Restructure it like so:
print(sentence)
sentence_words = sentence.split(' ')
word = input("What word are you looking for?").upper() #asks what word they want
for (i, check) in enumerate(sentence_words): #orders the words
if (check == word):
print("your word is in this position:", i+1)
positionofword=i+1
break
else:
print("This didn't work")
I have a program that asks for input of a sentence, then asks for a word, and tells you the position of that word:
sentence = input("enter sentence: ").lower()
askedword = input("enter word to locate position: ").lower()
words = sentence.split(" ")
for i, word in enumerate(words):
if askedword == word :
print(i+1)
#elif keyword != words :
#print ("this not")
However I cannot get the program to work correctly when I edit it to say that if the input word is not in the sentence, then print "this isn't in the sentence"
Lists are sequences, as such you can use the in operation on them to test for membership in the words list. If inside, find the position inside the sentence with words.index:
sentence = input("enter sentence: ").lower()
askedword = input("enter word to locate position: ").lower()
words = sentence.split(" ")
if askedword in words:
print('Position of word: ', words.index(askedword))
else:
print("Word is not in the given sentence.")
With sample input:
enter sentence: hello world
enter word to locate position: world
Position of word: 1
and, a false case:
enter sentence: hello world
enter word to locate position: worldz
Word is not in the given sentence.
If you're looking to check against multiple matches then a list-comprehension with enumerate is the way to go:
r = [i for i, j in enumerate(words, start=1) if j == askedword]
Then check on whether the list is empty or not and print accordingly:
if r:
print("Positions of word:", *r)
else:
print("Word is not in the given sentence.")
Jim's answer—combining a test for askedword in words with a call to words.index(askedword)—is the best and most Pythonic approach in my opinion.
Another variation on the same approach is to use try-except:
try:
print(words.index(askedword) + 1)
except ValueError:
print("word not in sentence")
However, I just thought I'd point out that the structure of the OP code looks like you might have been attempting to adopt the following pattern, which also works:
for i, word in enumerate(words):
if askedword == word :
print(i+1)
break
else: # triggered if the loop runs out without breaking
print ("word not in sentence")
In an unusual twist unavailable in most other programming languages, this else binds to the for loop, not to the if statement (that's right, get your editing hands off my indents). See the python.org documentation here.
I have created a program in python that basically tells the user to enter a word and tells them if it's a palindrome or not.
My program:
def palindrome(word):
return word == word[::-1]
word = input("Enter a word: ")
word2 = word.lower()
if word2 == "":
print("You failed to input a word")
elif palindrome(word2) == True:
print(word2,"is a palindrome!")
else:
print(word2,"is not a palindrome!")
I need help modifying my program so that it allows the user to enter a sentence and counts the number of words in the sentence that are palindromes. When I execute the program I would want it to output the palindromes in the sentence.
I've been struggling with this for days and I can't seem to figure out where to start. Help would be much appreciated. Also, I need to MODIFY my program above, not make a completely different program.
You need to split the string into words then check if each word is a palindrome using a list comp, the length of the list will also give you the count:
def palindrome(word):
return word == word[::-1]
# split sentence into words and filter out the non palindromes
sentence = [w for w in input("Enter a sentence: ").split() if palindrome(w)]
print(" There are {} palindromes in your sentence\n.".format(len(sentence)))
# print each palindrome from our list
for pal in sentence:
print("{} is a palindrome".format(pal))
If you want to mimic your own code, keep a count as you iterate over the list of words increasing the count if we have a palindrome:
sentence = input("Enter a sentence: ").split()
count = 0
for w in sentence:
if palindrome(w):
count += 1
print("{} is a palindrome.")
else:
print("{} is not a palindrome.")
print(" There are {} palindromes in your sentence\n.".format(count))
To catch single non-letters:
def palindrome(word):
if len(word) > 1:
return word == word[::-1]
return word.isalpha()
I am using grok learning and I can't seem to get passed this problem. You need to make a program program where you can enter one word at a time, and be told how many unique words you have entered. You should not count duplicates. The program should stop asking for more words when you enter a blank line.
This is my current code:
words = []
word = input("Word: ")
while word != '':
words.append(word)
word = input("Word: ")
print('You know', len(words), 'unique word(s)!')
It counts the amount of words you enter but I can't figure out how to make it check it the word is unique. Here are the desired outputs:
Word: Chat
Word: Chien
Word: Chat
Word: Escargot
Word:
You know 3 unique word(s)!
Here is another:
Word: Katze
Word: Hund
Word: Maus
Word: Papagei
Word: Schlange
Word:
You know 5 unique word(s)!
>>> words = ['Chat', 'Chien', 'Chat', 'Escargot']
>>> set(words)
set(['Chien', 'Escargot', 'Chat'])
>>> "You know " + str(len(set(words))) + " unique word(s)!"
'You know 3 unique word(s)!'
Use a set if you do not want to store duplicates.
words = set() #initialize a set
word = input("Word: ")
while word != '':
words.append(word)
word = input("Word: ")
print('You know', len(words), 'unique word(s)!')
If you want to store all the elements irrespective of duplicates, use a list
If you want to find unique elements inside a list, do this:
myset = set(words) #Now, myset has unique elements
print('You know', len(myset), 'unique word(s)!')
Based on what you should have learnt by that point in the course, you can use an if statement to check if the word you're looking at is already in the words list, and only add it if it is not already in the list:
words = []
word = input("Word: ")
while word != '':
if word not in words:
words.append(word)
word = input("Word: ")
print('You know', len(words), 'unique word(s)!')
You'll learn more about sets (which are a more efficient way to solve this question) later in the course.