2

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?

Community
  • 1
  • 1
new
  • 79
  • 2
  • 9
  • 2
    Do you want to use [`set()`](https://docs.python.org/2/library/sets.html)? – Remi Guan Oct 04 '15 at 07:23
  • 1
    A fairly clear question but I think is probably asked elsewhere too. – RFlack Oct 04 '15 at 07:34
  • @RFlack I think so: http://stackoverflow.com/questions/7961363/python-removing-duplicates-in-lists – Remi Guan Oct 04 '15 at 07:38
  • unrelated: `print('You know', len(set(iter(lambda: input('Word: '), ''))), 'unique word(s)')` – jfs Oct 04 '15 at 07:55
  • @Kevin Guan (I'm still finding my way in this place) ... I guess my point is, with no disrespect to the OP, what aren't the Duplicate Police on this one. Im not at all sure how that works. – RFlack Oct 04 '15 at 13:56
  • @RFlack Hmm...however this question has a good answer, and it has been accepted. – Remi Guan Oct 04 '15 at 13:58

1 Answers1

4

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)))
vaultah
  • 44,105
  • 12
  • 114
  • 143