DEV Community

Cover image for Python Collections: Hackerrank Question on Counter
Kathan Vakharia
Kathan Vakharia

Posted on • Updated on

Python Collections: Hackerrank Question on Counter

The Question

https://www.hackerrank.com/challenges/word-order/problem

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

  1. store the words as they come in the Counter.
  2. print them.

🧾 I hope you remember, Counter after python 3.7 internally maintains insertion order.

Code

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 mode Exit fullscreen mode

Top comments (2)

Collapse
 
aatmaj profile image
Aatmaj

That was smart! :-)

Collapse
 
kathanvakharia profile image
Kathan Vakharia

Thanks!😁