<문제>
링크 : https://www.acmicpc.net/problem/20291
20291번: 파일 정리
친구로부터 노트북을 중고로 산 스브러스는 노트북을 켜자마자 경악할 수밖에 없었다. 바탕화면에 온갖 파일들이 정리도 안 된 채 가득했기 때문이다. 그리고 화면의 구석에서 친구의 메시지를
www.acmicpc.net
<코드>
import sys
input = sys.stdin.readline # 시간 줄이기
N = int(input())
dict = {}
for i in range(N):
x, y = input().strip().split(".") # strip으로 공백 제거
if y in dict:
dict[y] += 1
else:
dict[y] = 1
for key in sorted(dict.keys()):
print(key, dict[key])
import sys
n = int(sys.stdin.readline())
ext_dict = {}
for i in range(n):
_, ext = sys.stdin.readline().rstrip().split(".")
if ext_dict.get(ext):
ext_dict[ext] += 1
else:
ext_dict[ext] = 1
for key in sorted(ext_dict.keys()):
print('{} {}'.format(key, ext_dict[key]))
# Counter 사용하기
import sys
input = sys.stdin.readline
from collections import Counter
N = int(input())
name = []
for i in range(N):
_, x = input().strip().split('.')
name.append(x)
counter = sorted(Counter(name).most_common())
for i in range(len(counter)):
print('{} {}'.format(counter[i][0], counter[i][1]))
<풀이>
- dictionary 타입으로 key와 value로 특정 key가 존재하면 값을 +1 해주고 새로운 값이라면 추가하여 1 값을 넣어준다.
- split을 하기 위해 strip()으로 공백 제거를 실시한다. 이를 하지 않고 그냥 split을 하면 공백과 줄바꿈이 포함된다.
- key값을 알면 dict[key]로 바로 value에 접근이 가능하다.
- strip을 통해 공백 제거 +) strip/lstrip/rstrip
- dictionary에 key가 있는지 확안 : if key in dict
- sorted(dict.keys()) : key값만 정렬하여 보여줌
- sorted(dict.items()) : key값 정렬 후 value와 같이 보여줌
참고 : https://github.com/Junuux/Algorithm/tree/main/Silver/20291
GitHub - Junuux/Algorithm
Contribute to Junuux/Algorithm development by creating an account on GitHub.
github.com
'Algorithm' 카테고리의 다른 글
백준 2022번 : 사다리 (0) | 2022.02.12 |
---|---|
백준 1654번 : 랜선 자르기 (0) | 2022.02.12 |
백준 19948번 : 음유시인 영재 (0) | 2022.01.25 |
백준 17413번 : 단어 뒤집기 2 (0) | 2022.01.25 |
백준 1972번 : 놀라운 문자열 (0) | 2022.01.25 |