Post
생태학(백준 4358번) | Gihun Son

생태학(백준 4358번)

문제

생태학에서 나무의 분포도를 측정하는 것은 중요하다. 그러므로 당신은 미국 전역의 나무들이 주어졌을 때, 각 종이 전체에서 몇 %를 차지하는지 구하는 프로그램을 만들어야 한다.

Untitled

Untitled 1

나의 풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import sys

tree_dic=dict()
count=0
while True:
    tree=sys.stdin.readline().strip()
    if tree=='':
        break
    if tree in tree_dic.keys():
        tree_dic[tree]+=1
    else:
        tree_dic[tree]=1
    count+=1
sorted_tree=sorted(tree_dic.items())
for s in sorted_tree:
    #print("{0} {1}".format(s[0],round((s[1]/count)*100,4)))
    print('%s %.4f' %(s[0],s[1]/count*100))
  • 나는 round()함수를 이용해서 반올림을 했는데, 계속 틀렸다고 나왔다.
    • round()함수는 ‘round half to even’방식이기 때문

      반올림 시 이전 수가 5이면, 짝수쪽으로 반올림한다. 만약 3.5이면 4로, 4.5여도 4로 반올림하는 것


추가적인 문법

  • f-string
    • f-string 사용방법
    1
    2
    3
    4
    5
    6
    
      # 문자열 맨 앞에 f를 붙이고, 출력할 변수, 값을 중괄호 안에 넣습니다.
      s = 'coffee'
      n = 5
      result1 = f'저는 {s}를 좋아합니다. 하루 {n}잔 마셔요.'
      print(result1)
        
    

    출처: https://blockdmask.tistory.com/429

    • f-string을 통한 소수점 반올림
    1
    2
    3
    4
    5
    
      print(f"{변수명:.0f}")
      print(f"{변수명:.1f}")
      print(f"{변수명:.2f}")
      print(f"{변수명:.3f}")
      print(f"{변수명:.43f}")
    
  • %서식 문자 이용

    print('%s %.4f' %(s[0],s[1]/count*100))

This post is licensed under CC BY 4.0 by the author.