Finding the percentage
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
result = sum(student_marks[query_name])/len(student_marks[name])
print("{:.2f}".format(result))
해설
파이썬 딕셔너리 타입을 이용하여 Key값에 해당하는 value값의 평균을 구하는 코드이다.
dictionary type
파이썬에서 닥셔너리는 자료형 타입으로 Key에 대응하는 Value를 얻을 수 있는 관계형 사전이다.
>>> stock = {'삼성전자': '005930', 'LG전자': '066570'}
>>> stock['삼성전자']
'005930'
>>> stock['LG전자']
'066570'
딕셔너리 관련 유용한 함수는 다음과 같다.
keys
>>> stock = {'삼성전자': '005930', 'LG전자': '066570'}
>>> stock.keys()
dict_keys(['삼성전자', 'LG전자'])
>>> list(stock.keys())
['삼성전자', 'LG전자']
dict_keys 객체를 리스트로 변환하기
values
>>> stock.values()
dict_values(['005930', '066570'])
>>> list(stock.values())
['005930', '066570']
items
>>> stock.items()
dict_items([('삼성전자', '005930'), ('LG전자', '066570')])
>>> list(stock.items())
[('삼성전자', '005930'), ('LG전자', '066570')]
get
>>> stock = {'삼성전자': '005930', 'LG전자': '066570'}
>>> stock.get('삼성전자')
'005930'
>>> stock['삼성전자']
'005930'
>>> stock.get('현대전자')
>>> stock['현대전자']
KeyError: '현대전자'
key값을 통해 value값을 얻는 방식이다. 위 stock['Key']와 유사한 방법이다.
차이점은 Key가 없는 경우 stock['현대전자']는 Key오류를 발생시키고, stock.get('현대전자')는 None을 돌려준다.
in
>>> stock = {'삼성전자': '005930', 'LG전자': '066570'}
>>> '삼성전자' in stock
True
>>> '현대전자' in stock
False
Sum
>>> student_marks = {'Krishna':[67,68,69], 'Arjun':[70,98,63], 'Malika':[52,56,60]}
>>> student_marks['Krishna']
[67,68,69]
>>> sum(student_marks['Krishna'])
204
sum은 숫자의 합을 구하는 함수이다.
student_marks[name]에 sum 함수를 적용하는 경우, 대응하는 해당 value 값의 합계를 알 수 있다.
len
>>> student_marks = {'Krishna':[67,68,69], 'Arjun':[70,98,63], 'Malika':[52,56,60]}
>>> student_marks['Krishna']
[67,68,69]
>>> len(student_marks['Krishna'])
3
len은 요소의 개수를 구하는 함수이다
student_marks[name]에 len 함수를 적용하는 경우, 대응하는 해당 value 값의 개수를 알 수 있다.
"{:.2f}".format()
>>> result = 3.141592
>>> print("{:.2f}".format(result))
3.14
"{:.자릿수f}".format(입력받는 숫자)은 입력받은 실수를 소수점 ㅇㅇ자릿수까지 표시하는 방법이다.
>>> result = 3.141592
>>> print("{:.2%}".format(result))
314.16%
"{:.자릿수%}".format(입력받는 숫자)은 입력받은 실수를 소수점 ㅇㅇ자릿수의 %로 표시하는 방법이다.
자동으로 100이 곱해지므로 3.14%가 아닌 314.16%가 나온다.
>>> result = 3.141592
>>> result = result / 100
>>> print("{:.2%}".format(result))
3.14%
만약에 3.14%를 의도했다면 위와 같은 방법으로 코드를 작성해야 한다.
'Develop > hackerrank.com' 카테고리의 다른 글
HackerRank Python Solution / Tuples (0) | 2022.01.11 |
---|---|
HackerRank Python Solution / Lists (0) | 2022.01.10 |
HackerRank Python Solution / Nested List (0) | 2022.01.07 |
HackerRank Python Solution / Find the Runner-Up Score! (0) | 2022.01.01 |
HackerRank Python Solution / List Comprehensions (0) | 2022.01.01 |