【问题标题】:Python: Creating a function that returns a list of scores in a competitionPython:创建一个返回竞赛分数列表的函数
【发布时间】:2020-08-15 00:54:28
【问题描述】:

我在创建具有以下条件的函数时遇到了问题。我认为我的函数有时会得出正确的答案是巧合。

  • 在一场比赛中,进入下一轮的规则是“如果一个选手的得分等于或大于第k名的人,他们将进入下一轮,只要得分大于或等于 [limit]”。
  • 编写一个函数 next_round(k, limit, scores)。
  • 以整数形式返回进入下一轮的人数。
  • scores 是包含所有其他参赛者得分的列表,不分先后。
  • 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)

谢谢!

【问题讨论】:

  • 从您正在迭代循环的列表中删除元素绝不是一个好主意。因为,你最终会跳过索引。所以,看看these approaches
  • 最后一个项目符号的措辞是否正确?不应该说“如果有多个人的分数与第 k 个人的分数相同且分数大于或等于限制...”吗?换句话说,next_round(1, 2, [1, 2, 2, 2]) 应该打印什么?最后一个项目符号当前的措辞方式将返回1。使用“或等于”,它将返回3
  • @RustyWidebottom 嗨,这就是我老师在问题中的措辞。 :S

标签: python


【解决方案1】:

让我知道最后一个项目符号,我会相应地更新我的答案。

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

【讨论】:

  • 嗨!它似乎也像我的一样工作,但是有一个似乎没有得到正确的答案,这就是我正在做的事情,这个也是,但我不知道为什么。 print(next_round(10, 20, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) 应该返回 5 但函数返回 0。
  • [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 中的所有分数均低于限制 (20)。因此没有人前进。
  • 哦,等等,对不起,我把我的数字和功能弄混了!谢谢哈哈。 :)
猜你喜欢
  • 2011-02-19
  • 1970-01-01
  • 2019-04-14
  • 2023-01-12
  • 2016-10-12
  • 2013-10-22
  • 2013-11-05
  • 1970-01-01
  • 2021-12-17
相关资源
最近更新 更多