You are given an integer array score of size n, where score[i] is the score of the ith athlete in a competition. All the scores are guaranteed to be unique.
The athletes are placed based on their scores, where the 1st place athlete has the highest score, the 2nd place athlete has the 2nd highest score, and so on. The placement of each athlete determines their rank:
The 1st place athlete's rank is "Gold Medal".
The 2nd place athlete's rank is "Silver Medal".
The 3rd place athlete's rank is "Bronze Medal".
For the 4th place to the nth place athlete, their rank is their placement number (i.e., the xth place athlete's rank is "x").
Return an array answer of size n where answer[i] is the rank of the ith athlete.
n == score.length
1 <= n <= 104
0 <= score[i] <= 106
All the values in score are unique.
class Solution:
def findRelativeRanks(self, score):
sorted_scores = sorted(score, reverse=True) # 점수 내림차순 정렬
rank_map = {score: str(i + 1) for i, score in enumerate(sorted_scores)}
if len(sorted_scores) > 0:
rank_map[sorted_scores[0]] = "Gold Medal"
if len(sorted_scores) > 1:
rank_map[sorted_scores[1]] = "Silver Medal"
if len(sorted_scores) > 2:
rank_map[sorted_scores[2]] = "Bronze Medal"
return [rank_map[s] for s in score]
생각보다 어렵지 않게 풀 수 있었으나 함수 안에 작성하는 게 헷갈렸던 것 같다. 아무래도 파이썬 함수 부분을 많이 까먹어서 그런 것 같다.
score
라는 리스트가 주어졌을 때, 점수가 높은 순서대로 1등, 2등, 3등을 정하고 그 이후의 순위는 숫자로 표기한다고 했다.
enumerate()
를 이용해서 (인덱스, 점수)
형태의 쌍을 생성하고 딕셔너리로 저장한 다음, 리스트의 최소 요소를 고려하여 점수가 가장 많은 순서대로 금, 은, 동 메달을 부여한다.
그리고 원래 리스트에 담긴 순서대로 값을 출력하도록 하면 정답이다. if
문 같은 경우에는 리스트 안에 요소가 몇 개인지에 따라 값이 달라질 수 있기 때문에 위와 같이 처리를 해주었다.
enumerate()
: 파이썬에서 반복문을 돌릴 때, 인덱스와 값을 동시에 가져올 수 있는 함수이다. 보통 아래와 같은 형태로 작성해서 인덱스, 값 쌍으로 출력 받을 수 있다.fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
# 출력 결과
0 apple
1 banana
2 cherry
enumerate()
는 기본적으로 0부터 인덱스가 시작하지만 enumerate(리스트_이름, start=1)
과 같이 작성하면 원하는 숫자부터 시작하도록 조정할 수 있다.