일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- hackerrank
- AI 경진대회
- Kaggle
- programmers
- 금융문자분석경진대회
- PYTHON
- 자연어처리
- Baekjoon
- 코로나19
- 더현대서울 맛집
- 파이썬
- 데이콘
- leetcode
- 프로그래머스 파이썬
- 캐치카페
- Docker
- 편스토랑 우승상품
- dacon
- github
- 우분투
- Git
- 맥북
- SW Expert Academy
- 백준
- gs25
- Real or Not? NLP with Disaster Tweets
- 프로그래머스
- ChatGPT
- 편스토랑
- ubuntu
- Today
- Total
솜씨좋은장씨
[BaekJoon] 4358번 : 생태학 (Python) 본문

코딩 1일 1문제! 오늘의 문제는 백준의 생태학 입니다.
백준의 생태학을 파이썬으로 풀이하였습니다.
4358번: 생태학
프로그램은 여러 줄로 이루어져 있으며, 한 줄에 하나의 나무 종 이름이 주어진다. 어떤 종 이름도 30글자를 넘지 않으며, 입력에는 최대 10,000개의 종이 주어지고 최대 1,000,000그루의 나무가 주어
www.acmicpc.net
👨🏻💻 문제 풀이

생태학 이 문제는.... 여러번의 시간 초과 이후에 백준의 흔한 시간 초과 해결 방법인
input() -> sys.stdin.readline() 변경 이후 맞았습니다를 볼 수 있었던 문제입니다...
while 반복문을 잘 못 다뤄서 시간 초과가 나는건가 생각되어 한참 고민했던 문제입니다.
이 문제는 Dictionary를 잘 활용하면 풀 수 있는 문제입니다.
Dictionary에 나무이름을 키로하고 각 나무의 개수를 해당 나무 이름 키의 위치에서 증가 시켜준 뒤
tree_dict = {}
tree_name_list = set()
tree_num = 0
while True:
tree = input().rstrip()
if not tree:
break
tree_num += 1
if tree not in tree_dict.keys():
tree_dict[tree] = 1
tree_name_list.add(tree)
else:
tree_dict[tree] += 1
tree_names = sorted(list(tree_name_list))
나중에 하나씩 꺼내어 전체 나무개수로 나누고 100을 곱하여 백분율을 구해주고
이를 f-string을 활용하여 원하는 모양으로 출력하면서 소수점 4자리 수 까지 .4f 로 표현합니다.
tree_dict, tree_names, tree_num = ecology()
for tree in tree_names:
print(f"{tree} {((tree_dict[tree] / tree_num) * 100):.4f}")
그런데 여기서 input() 을 그대로 사용하면! 시간초과... 가 발생합니다.
from sys import stdin
input = stdin.readline
이에 맨 위에 input을 sys.stdin.readline으로 바꾸어주는 코드를 넣어주면 맞았습니다! 를 보실 수 있습니다.
전체 코드는 아래를 참고해주세요.
👨🏻💻 코드 ( Solution )
from sys import stdin
input = stdin.readline
def ecology():
tree_dict = {}
tree_name_list = set()
tree_num = 0
while True:
tree = input().rstrip()
if not tree:
break
tree_num += 1
if tree not in tree_dict.keys():
tree_dict[tree] = 1
tree_name_list.add(tree)
else:
tree_dict[tree] += 1
tree_names = sorted(list(tree_name_list))
return tree_dict, tree_names, tree_num
if __name__ == "__main__":
tree_dict, tree_names, tree_num = ecology()
for tree in tree_names:
print(f"{tree} {((tree_dict[tree] / tree_num) * 100):.4f}")
GitHub - SOMJANG/CODINGTEST_PRACTICE: 1일 1문제 since 2020.02.07
1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.
github.com
'Programming > 코딩 1일 1문제' 카테고리의 다른 글
[BaekJoon] 4458번 : 첫 글자를 대문자로 (Python) (2) | 2021.09.09 |
---|---|
[BaekJoon] 1755번 : 숫자놀이 (Python) (0) | 2021.09.08 |
[Programmers] 위클리 챌린지 6주차 - 복서 정렬하기 (Python) (0) | 2021.09.06 |
[BaekJoon] 5800번 : 성적 통계 (Python) (0) | 2021.09.05 |
[BaekJoon] 2776번 : 암기왕 (Python) (0) | 2021.09.04 |