본문 바로가기
Problem Solving

[백준 BOJ - 4358 / 파이썬] 생태학

by Oh Seokjin 2022. 9. 4.

4358번: 생태학 (acmicpc.net)

 

4358번: 생태학

프로그램은 여러 줄로 이루어져 있으며, 한 줄에 하나의 나무 종 이름이 주어진다. 어떤 종 이름도 30글자를 넘지 않으며, 입력에는 최대 10,000개의 종이 주어지고 최대 1,000,000그루의 나무가 주어

www.acmicpc.net

 

🔍 문제 분석

등장하는 원소 비율을 정렬해서 출력하는 문제

 

❗ 해결 아이디어 

입력이 들어오지 않을 때까지 입력받는 방법을 배웠다.

이외의 부분은 딕셔너리를 활용해 비율을 계산하면 된다. 

 

✔️ 최종 풀이

import sys

dict_of_trees = {}

while True:
    type_of_tree = sys.stdin.readline().rstrip()
    if not type_of_tree:
        break
    if type_of_tree not in dict_of_trees:
        dict_of_trees[type_of_tree] = 0
    dict_of_trees[type_of_tree] += 1

dict_of_trees = dict(sorted(dict_of_trees.items()))
total_count = sum(dict_of_trees.values())

for elem in dict_of_trees.keys():
    print(f"{elem} {dict_of_trees[elem] / total_count * 100:0.4f}")

댓글