6

Python Collections: Hackerrank Question on Counter

 2 years ago
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

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.

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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK