1 사용한 자료구조 및 개념 : 딕셔너리, Counter
💡 문제풀이 아이디어 및 어려웠던 점
💫 아이디어
1️⃣ 딕셔너리를 사용하여 나무이름: 나무 갯수 로 키 - 값을 설정한다.
2️⃣ 딕셔너리에 나무가 있다면 value값을 +1해주고 없다면 딕셔너리에 나무이름-값을 추가한다.
3️⃣ 알파벳 순서로 딕셔너리를 정렬한다.
4️⃣ 정렬한 딕셔너리를 반복문으로 돌려 키 값을 가져와 나무 이름과 해당 나무가 전체 나무에서 차지하는 비율을 출력한다.
❣️ Counter 사용
1️⃣ 모든 텍스트를 읽고, 줄 바꿈을 기준으로 각 나무 이름을 Counter 을 사용하여 카운트 한다.
2️⃣ split(’n’)을 하면 마지막에 빈 문자열(””)이 생길 수 있으므로 빈 문자열을 딕셔너리에서 삭제한다.
3️⃣ 알파벳 순서로 딕셔너리를 정렬한다.
4️⃣ 나무 이름과 해당 나무가 전체 나무에서 차지하는 비율을 출력한다.
Solution Code & 주석
# 딕셔너리 활용
import sys
trees = {}
total = 0
while True:
tree = sys.stdin.readline().rstrip()
if not tree:
break
if not trees.get(tree):
trees[tree] = 1
else:
trees[tree] += 1
total += 1
ordered_trees = sorted(trees.items())
for tree, num in ordered_trees:
print(f'{tree} {num/total*100:.4f}')
# Counter
import sys
from collections import Counter
trees = Counter(sys.stdin.read().split("\\n"))
del trees[""]
total = sum(trees.values())
ordered_trees = sorted(trees.items())
for tree, num in ordered_trees:
print(f"{tree} {100 * num / total:.4f}")
'💡Algorithm > python' 카테고리의 다른 글
[python]2696_중앙값 구하기 (0) | 2023.08.23 |
---|---|
[python]11286_절대값 힙 (0) | 2023.08.11 |
[python]1620_나는야 포켓몬 마스터 이다솜 (0) | 2023.08.07 |
[python]1918_후위 표기식 (0) | 2023.08.01 |
[python]22942_데이터 체커 (0) | 2023.07.14 |