6
Python Collections: Hackerrank Question on Counter
source link: https://dev.to/kathanvakharia/python-collections-hackerrank-question-on-counter-80i
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
The Question
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.
The Approach
- store the words as they come in the Counter.
- print them.
🧾 I hope you remember,
Counter
after python 3.7 internally maintains insertion order.
from collections import Counter
words = list()
#n -> no of words
n = int(input())
for _ in range(n):
words.append(input())
#
c =Counter(words)
print(len(c))
print(*c.values())
Enter fullscreen modeExit fullscreen mode
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK