Prepare > Python > Collections > Word Order

2023. 9. 22. 19:57HackerRank-Python

 

Word Order | HackerRank

List the number of occurrences of the words in order.

www.hackerrank.com

 

문제


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.

Input Format

The first line contains the integer, n.
The next n lines each contain a word.

 

Output Format

Output 2 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.

 

 

 

 

코드


from collections import defaultdict

d = defaultdict(int)
N = int(input())

for i in range(N):
    d[input()] += 1

 
print(len(d.keys()))
print(*d.values())

 

 

 

 

노트


defaultdict

defaultdict(int)를 주면 키 값을 넘겨줄 때, 0을 자동으로 설정해주는듯?

from collections import defaultdict

d = defaultdict(int)
N = int(input())

for i in range(N):
    print(d)
    d[input()] += 1
    print(d)
더보기
defaultdict(<class 'int'>, {})
defaultdict(<class 'int'>, {'bcdef': 1})
defaultdict(<class 'int'>, {'bcdef': 1})
defaultdict(<class 'int'>, {'bcdef': 1, 'abcdefg': 1})
defaultdict(<class 'int'>, {'bcdef': 1, 'abcdefg': 1})
defaultdict(<class 'int'>, {'bcdef': 1, 'abcdefg': 1, 'bcde': 1})
defaultdict(<class 'int'>, {'bcdef': 1, 'abcdefg': 1, 'bcde': 1})
defaultdict(<class 'int'>, {'bcdef': 2, 'abcdefg': 1, 'bcde': 1})

 

 

 

 

참조


 

Prepare > Python > Collections > DefaultDict Tutorial

DefaultDict Tutorial | HackerRank Create dictionary value fields with predefined data types. www.hackerrank.com 문제 Input Format The first line contains integers, n and m separated by a space. The next n lines contains the words belonging to group A. Th

my-little-diary.tistory.com