chae._.chae

[Algorithm] 백준 #20920 영단어 암기는 괴로워 본문

파이썬 알고리즘/BOJ

[Algorithm] 백준 #20920 영단어 암기는 괴로워

walbe0528 2024. 7. 8. 00:59
728x90
반응형

 

 

import sys
from collections import defaultdict
input = sys.stdin.readline

N, M = map(int, input().split())
words = []
words_dict = defaultdict(int)
for _ in range(N):
    word = input().rstrip()
    words.append(word)
    words_dict[word] += 1

for key in list(words_dict):
    if len(key) < M:
        del words_dict[key]
words_dict = sorted(words_dict.items(), key=lambda x:(-x[1], -len(x[0]), x[0]))  # key값 내림차순

# print(words_dict)
for key, _ in words_dict:
    print(key)

 

 

📌 다시 봐야 할 부분

 

1. 딕셔너리에서 아래처럼 for문을 통해 key으로 제거하려 하면 오류남

for key, value in words_dict.items():
    if len(key) < M:
        del words_dict[key]
print(words_dict)

 

RuntimeError: dictionary changed size during iteration 오류 발생
iteration을 수행하는 도중에 key가 삭제되면 사이즈 변경을 인지하여 runtime 에러를 발생
list로 바꿔서 수행

 

2. defalutdict 말고 Counter 모듈도 있다

from collections import Counter

 

딕셔너리처럼 활용하려면

>>> counter = Counter("hello world")
>>> counter 
Counter({'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1})

>>> counter["o"], counter["l"]
(2, 3)
728x90