-3

We were tasked to create a program that counts the total numbers of unique words from a user input and we are not allowed to use sets and dictionaries. Words with duplicates or identical words should not be counted. I have a code and it works with other inputs but when I input "facebook face face book" or something similar it counts 3 instead of 2.

def unique_counter():
    words = input().lower().split()
    unique_words = {}
    for word in words:
        try:
             unique_words[word] += 1
        except KeyError:
             unique_words[word] = 1
    print(len(unique_words))


unique_counter()

similar input input with correct output

1 Answers1

0

As soon as you can't use dictionaries, I would use the in operator.

def unique_counter():
    unique_words = []
    words = input().lower().split()
    for word in words:
        if word not in unique_words:
            unique_words.append(word)
    print(f"there are {len(unique_words)} unique words in the phrase")

if you have to check also substrings (you expect that the input "face facebook" gives "face" and "book" as unique words), then it's a bit more complicated.

if you have to count how many times that word is used, then it's pretty complex without using dictionaries.