2023. 9. 22. 19:57ㆍHackerRank-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
'HackerRank-Python' 카테고리의 다른 글
Prepare > Python > Collections > Company Logo (0) | 2023.09.25 |
---|---|
Prepare > Python > Collections > Piling Up! (0) | 2023.09.22 |
Prepare > Python > Itertools > Compress the String! (0) | 2023.09.20 |
Prepare > Python > Itertools > Iterables and Iterators (0) | 2023.09.19 |
Prepare > Python > Sets > No Idea! (0) | 2023.09.16 |