백준 25206번 너의 평점은
문제
전공평점은 (학점 × 과목평점)의 합을 학점의 총합으로 나눈 값이다. 과목평점은 A+ 4.5, A0 4.0, B+ 3.5, B0 3.0, C+ 2.5, C0 2.0, D+ 1.5, D0 1.0, F 0.0이고, 등급이 P인 과목은 계산에서 제외한다. 20줄에 걸쳐 과목명, 학점(1.0, 2.0, 3.0, 4.0 중 하나), 등급이 공백으로 구분되어 주어지고, 전공평점을 출력한다. 절대오차 또는 상대오차가 10의 -4제곱 이하이면 정답이다.
풀이
등급별 점수를 딕셔너리 dict_grade에 담아 두고, 입력 20줄을 읽으면서 학점 × 과목평점을 total_score에, 학점을 total_point에 더한다. 등급이 P인 줄은 둘 다 더하지 않고 건너뛴다. 마지막에 total_score / total_point를 출력한다.
# 학점을 반환할 딕셔너리 생성
dict_grade = {
"A+": 4.5,
"A0": 4.0,
"B+": 3.5,
"B0": 3.0,
"C+": 2.5,
"C0": 2.0,
"D+": 1.5,
"D0": 1.0,
"F": 0
}
total_score = 0 # 학점 * 등급 (총 평점)
total_point = 0 # 총 이수학점
for _ in range(20):
# 과목, 학점, 등급을 string으로 받음
subject, point, grade = map(str, input().split())
point = float(point) # 학점은 따로 float 처리
# Pass는 학점 계산 제외
if grade == 'P':
continue
else:
total_score += dict_grade[grade] * point
total_point += point
# 총 평점 / 총 이수학점
print(total_score/total_point)처음 시도한 풀이
처음에는 while문과 등급을 점수로 바꾸는 함수를 따로 만들어 풀었는데, 일부 과목이 계속 건너뛰어졌다.
def grade_(input):
score = 0
if input == 'P' or input == 'F':
return 0.0
elif input[0] == 'A':
score = 4.0
elif input[0] == 'B':
score = 3.0
elif input[0] == 'C':
score = 2.0
else:
score = 1.0
if input[-1] == '+':
return score + 0.5
else:
return score
total_score = 0
total_point = 0
while True:
if len(input()) > 0:
list_score = list(map(str, input().strip().split()))
point = float(list_score[1])
if list_score[-1] == 'P':
continue
else:
score = grade_(list_score[-1])
total_score += score * point
total_point += point
else:
break
print(total_score / total_point)이 코드는 if len(input()) > 0: 에서 한 줄을 읽고, 바로 아래 input()으로 다음 줄을 또 읽는다. 그래서 두 줄에 한 줄씩만 계산에 쓰이고 나머지는 버려진다. 한 번 읽은 줄을 변수에 담아 조건 검사와 계산에 같이 써야 한다.