HackerRank Python Find the Runner-Up Score! 解法
YC JHUO 4/15/2021 PythonHackerRankEasy
# Problem
Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given n
scores. Store them in a list and find the score of the runner-up.
# Input Format
The first line contains n
. The second line contains an array A[ ]
of n
integers each separated by a space.
# Constraints
- 2 <=
n
<= 10 - -100 <=
A[i]
<= 100
# Output Format
Print the runner-up score.
# Sample Input
5
2 3 6 6 5
# Sample Output
5
# Explanation 0
Given list is [2, 3, 6, 6, 5 ]
. The maximum score is 6
, second maximum is 5
.
Hence, we print 5
as the runner-up score.
# Answer
這題的題目是 輸入二個變數 n 及 arr
n 用來限制 arr 裡面有幾個值,arr 則是給定數個數字(中間用空格隔開),最後要輸出 arr 中第二大的數字(runner-up)
下面我們用 n 輸入 5,arr 輸入 2 3 6 6 5 2 3 來舉例:
# Source Code
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
# Write your code below :
# 首先,先將 arr 轉為 list 型態,並在後面加上 [:n] 來限制 arr 的長度為我們所輸入的 n
arrList = list(arr)[:n]
# 取得目前 arrList 中最大的數字
maxNumber = max(arrList) # 這時 maxNumber 會是 6
# 若 arrList 有 6 的話,則移除
while (maxNumber in arrList):
arrList.remove(maxNumber)
# 執行完 while 後,arrList 會變成 2 3 5 2 3 (所有的 6 都已被移除)
# 這時在用 max 取出 arrList 中最大的數,即可得到原先 arrList 中,第二大的數字(runner-up),也就是 5
runnerUp = max(arrList)
print(runnerUp)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
歡迎點擊追蹤: