0
words=[]
word=input("Word:")
count=0
while word != '':
    count+=1
    words.append(word) 
    word=input("Word:")
    for w in words:
        if words.count(w)>1:
            count-=1 

print("You know",count,"unique word(s)")

So what my code does is, it allows the user to input words and then checks to see if they have any duplicate words; if they do, it doesn't count. So after that's done it tells you how many 'unique words' you know.

The problem is: when there are no duplicates it outputs the right amount of 'unique words' however when there are duplicates it outputs the 'right amount of unique words' - 1. So let's say i give in 3 words and 2 of them are duplicates; it will say there's only 1 unique word. Thank you for any help.

2 Answers 2

1

It might help to understand what's going on if you add print(words) after words.append(word).

What happens is that word gets added as a new item to the array. In the loop where you decrement count you decrement for each word that is not unique, i.e. if a word occurs twice you decrement twice.

Input          words           count
a              [a]               1
a, b           [a, b]            2
a, b, b        [a, b, b]         1
a, b, b, b     [a, b, b, b]     -1
a, b, b, c, c  [a, b, b, c, c]  -3

Another problem is that the for-loop happens after each input, i.e. you decrement the same duplicate multiple times.

A fixed version of your program that keeps inputing individual words would be

words=[]
word=input("Word:")
while word != '':
    words.append(word)
    word=input("Word:")

uniquewords = set(words)
print("You know",len(uniquewords),"unique word(s)")
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for taking your time to answer my question, thank you to the other person who helped as well, it was much appreciated.
0

You can split the user's input on a space and then add the item into a set instead. A set contains unique items, so adding "a" to it three times would result in only containing one "a".

word = input('Word:')
split_word = word.split() # splits on space
set_word = set(split_word) # turns the list into a set
unique_words = len(set_word)
print("You know",unique_words,"unique word(s)")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.