DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 967,611 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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 Author

Thanks!😁

Take a look at this:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. πŸ›