
Python Word Order - Another Hacker Rank Solution
Aug 29
2 min read
0
17
0

Consider the following problem.
You are given a number of words to read into your python program.
The output needs to have on the first line - the number of unique words.
On the second line, there needs to be a number for each unique word detailing how many times that word has appeared in the input.
The numbers need appear in the order that the word does.
Below is the problem from hacker rank:
You are given n words. Some words may repeat. For each word, output its number of occurrences. The output order should correspond with the input order of appearance of the word. See the sample input/output for clarification.
Output lines.
On the first line, output the number of distinct words from the input.
On the second line, output the number of occurrences for each distinct word according to their appearance in the input.
Below are listed a sample input and sample output.


So how do we turn that input into that output?
Using this code:

First, we read in the input.
Second, we place all words in a list called words.
We create an empty dictionary called word_dictionary.
We convert the word list to a set called y.
Sets cannot contain duplicate values so when we take the length of the set that is the number of unique words.
Next, we loop through the list words:
If the word does not already appear in the word_dictionary we add the key value pair with a value of one to the dictionary.
If the word is already in the word_dictionary then we update the value of the key value pair in the dictionary to be equal to the value of the value + 1.
Finally, we print the value of the word_dictionary on one line.
The snippet is below for ease of use:
n = int(input())
words = [input() for _ in range(n)]
word_dictionary = {}
y = set(words)
unique = len(y)
print(unique)
for word in words:
if word not in word_dictionary:
word_dictionary[word] = 1
else:
word_dictionary[word] = int(word_dictionary[word]) + 1
#print(word_dictionary)
for value in word_dictionary.values():
print(value, end=' ')





