0

I am trying to make a programme that takes words from the user, puts them in a list and then prints the amount of unique words that the user entered. The programme prints out the unique words when it receives a blank input. This is what I wrote.

amount = []
nuword = input('Word: ')
while nuword != '':
  nuword = input('Word: ')
  if nuword in amount:
    amount.pop(-1)
  else:
    amount.append(nuword)
print('You know',len(amount), 'unique word(s)!')

Is there a simple way to print all of the unique words in a list. Like some kind of function? Or do I have to change something in the loop?

Cian McGovern
  • 45
  • 1
  • 3

2 Answers2

0
counts = {}

nuword = 1
while nuword:
    nuword = input("Word: ")
    if nuword not in counts: counts[nuword] = 0
    counts[nuword] += 1

uniquewords = []
for word, count in counts.items():
    if count != 1: continue
    uniquewords.append(word)
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
0

This is an ideal candidate for sets, which are similar to lists, but only contain one copy of something.

Example set usage:

words = set()
words.add('apple')
words.add('bee')
words.add('apple')
print(words)
> {'apple', 'bee'}

Here is your code slightly modified to use sets

amount = set()
nuword = input('Word: ')
while nuword != '':
    nuword = input('Word: ')
    amount.add(nuword)
print('You know',len(amount), 'unique word(s)!')

I would also recommend considering the case of beginning/trailing spaces and upper/lower case. Right now, all of the following will count as their own word

abc
 abc
abc  
aBc

(Hint, the 3rd one had trailing spaces) We'll use some handy methods to get rid of the whitespace and turn to lower case.

' aBc   '.strip().lower()
> 'abc'

With all the edits:

amount = set()
nuword = input('Word: ')
while nuword != '':
    nuword = input('Word: ')
    amount.add(nuword.strip().lower())
print('You know',len(amount), 'unique word(s)!')
Sam Myers
  • 2,112
  • 2
  • 15
  • 13