I'm trying to write a program that stops if the same word is given twice. This code almost does the job, but it stops only if the duplicate words are given sequentially. Thanks for your help.
list = []
double = None
while True:
word = input("word: ")
lista.append(word)
if douple == word:
print(f"You gave {len(list)} words")
break
double = word
You need to check if the word is already in the list
seen = []
while True:
word = input("word: ")
if word in seen:
print(f"You gave {len(seen)} words")
break
seen.append(word)
If you just want to tell duplicates, and don't need to keep the order, you can use a set instead; this will be more efficient for a large number of words:
seen = set()
while True:
word = input("word: ")
if word in seen:
print(f"You gave {len(seen)} words")
break
seen.add(word)
Finally, in sufficiently recent Python (at least 3.6 or 3.7, depending on how you take things), you can do both by using a dictionary; this is both efficient and keeps the order in which the words were entered:
seen = {}
while True:
word = input("word: ")
if word in seen:
print(f"You gave {len(seen)} words")
break
seen[word] = None
Change your code to what is given below:
words_list = []
while True:
word = input("Word: ")
if word not in words_list: #Checks if the word is in the list. If it exists in list, it would return False
words_list.append(word)
else:
print(f"You gave {len(words_list)} words")
break
I have changed a few things:
Don't use list as a variable name as it is a keyword in Python.
Check for duplicate words using not in before you append it to the list. If word exists in the list, the loop would break.
This should do the work. You can always comment down if you need clarification or if the code dosen't work.
Related
I'm trying to find find the longest string entered then print it as the output value. The program stops running when an 'a' has been entered then returns the longest string entered not just the numbers of characters in the string. Can the length function do this?
def longest_str(words):
words = len(words)
return words
true = 1
while true: # start loop
words = str(input("Enter a string: "))
words = words.lower()
if words.startswith('a'): #comparing if starts with a or A
print(f"The longest string was: {longest_str(words)}") # printing output
break #stop once reached a
else:
continue # continue to loop through, no a was found.
I understand what you are trying to do but you have several mistakes
while true: # start loop
words = str(input("Enter a string: "))
words = words.lower()
This will read only one word at the time.
So, your if will be executed only if you enter a word starting with 'a'.
This will solve your problem
def longest():
maxLength = 0
longestWord = ''
while(True):
word = str(input("Enter a string: "))
word = word.lower()
if word == 'a':
print(f"The longest string was: {longestWord}")
break
if len(word) > maxLength:
maxLength = len(word)
longestWord = word
Take a look at the differences
We check if the word entered is 'a', then print the longest string and stop.
If not, we check if the new word is longer than what we previously had (initialy nothing).If the new word is longer, we retain it to be able to print it.
Just call this in the main function.
If you want the string itself you could just do it like this:
longest_string = ''
while True:
word = input("Enter a string: ").lower()
if word == 'a': break
if len(word) > len(longest_string):
longest_string = word
print("The longest string was: " + longest_string)
Keep in mind, this will make ALL words lowercase, if you dont want that you have to remove the .lower()
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)!")
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)!')
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 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.