簡體   English   中英

Python:創建一個 function 以返回比賽中的得分列表

[英]Python: Creating a function that returns a list of scores in a competition

我無法使用以下標准創建 function。 我認為這是一個巧合,我的 function 有時會提出正確的答案。

  • 在一場比賽中,進入下一輪的規則是“如果一個選手的得分等於或大於第 k 名的人,則如果得分大於或等於[限制]”。
  • 寫一個 function next_round(k, limit, scores)。
  • 返回人數為 integer 進入下一輪。
  • 分數是包含所有其他參賽者分數的列表,沒有特定的順序。
  • k 是進入下一輪的最大參賽者數量
  • limit 是進步所需的最低分數(即使你是第 k 名的人,除非你的分數大於 limit,否則你無法進步)。
  • 如果有多人與第k個人得分相同且得分大於限制,他們將全部晉級下一輪。 參賽者將不超過100人。

例子:

next_round(2, 3, [1, 3, 2, 4])
next_round(10, 5, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])

回報:

2
10

我的代碼:

def next_round(k, limit, scores):
"""Returns number of people progressing to the next round."""
for n in scores:
    if n > limit:
        del scores[k:]
    if n < limit:
        scores.remove(n) # I think my problem is here but not sure what to do.
return len(scores)

謝謝!

讓我知道最后一個項目符號,我會相應地更新我的答案。

def next_round(k, limit, scores):
    """Returns number of people progressing to the next round."""
    progressing = 0

    # Look at the top k scores.
    topk = sorted(scores, reverse=True)[:k]
    for score in topk:
        if score >= limit:
            progressing += 1

    # And also include people with the same score as the k-th
    # person with score greater than limit.  (last bullet)
    rest = sorted(scores, reverse=True)[k:]
    for score in rest:
        if score == topk[-1] and score > limit:
            progressing += 1

    return progressing

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM