new
new

Reputation: 79

How to not count the duplicates from an user input?

This is my current code:

words = []
word = input('Word: ')
while word != '':
  words.append(word)
  word = input('Word: ')
print("You know "+ str(len(words)), "unique word(s)!")

This is what I need:

Word: Chat

Word: Chien

Word: Chat

Word: Escargot

Word:

You know 3 unique word(s)!

It is not supposed to count any duplicate words. I'm not sure how to avoid this. Because I have done everything else except this. Is there an easy way, but a simple one?

Upvotes: 2

Views: 1112

Answers (1)

vaultah
vaultah

Reputation: 46573

Check if the word is already in the words list using the in operator:

words = []
word = input('Word: ')
while word != '':
    if word not in words:
        words.append(word)
    word = input('Word: ')
print("You know "+ str(len(words)), "unique word(s)!")

This will work well but membership testing is O(n) for lists. Consider using sets for faster lookup.

It'll be performed implicitly by the set.add method ("Add an element to a set. This has no effect if the element is already present.") :

words = set()
word = input('Word: ')
while word != '':
    words.add(word)
    word = input('Word: ')
print("You know "+ str(len(words)), "unique word(s)!")

Note that string formatting is better (and easier) way to format the output:

print("You know "+ str(len(words)), "unique word(s)!")

can be

print("You know {} unique word(s)!".format(len(words)))

Upvotes: 4

Related Questions