0

我是 python 的初学者,我有一个任务,winner_round 函数比较两个列表,并计算在游戏中有多少轮亚当的球队得分比对手多。如果两个列表不匹配,则返回 -1 这是我的代码:

def winner_round(list1,list2):
    list1 = [30, 50, 10, 80, 100, 40]
    list2 = [60, 20, 10, 20, 30, 20]
    point = 0
    for i in winner_round(list1,list2):
        if list1>list2:
            return -1
            print(-1)
    for pointA in list1:
        for pointE in list2:
            if pointA > pointE:
                point+=1
        break
    return(point)
    print(point)

对不起我的英语不好

4

4 回答 4

2

返回的唯一原因-1是列表的大小不同;len在您进行迭代之前,您可以使用 O(1) 操作进行检查。

之后,这只是列表项的逐点比较问题。假设list1是亚当和list2他的对手,

def winner_round(list1, list2):
    if len(list1) != len(list2):
        return -1

    return sum(x > y for x, y in zip(list1, list2))

zip(list1, list2)产生对(30, 60),(50, 20)等。因为True == 1and False == 0(bool是 的子类int),您可以简单地将结果相加,其中的值list1是一对中较大的值。

(您也可以使用map,因为 2 参数函数作为第一个参数允许您将两个列表作为第二个和第三个参数传递,从而无需对zip实例进行更明确的迭代。operator.gt提供您需要的函数:

return sum(map(operator.lt, list1, list2))

哪个“更好”是个人喜好问题。)

于 2020-10-03T20:28:42.213 回答
0

积分总和:

list1 = [30, 50, 10, 80, 100, 40]
list2 = [60, 20, 10, 20, 30, 20]

def winner_round(list1,list2):
    if sum(list1) > sum(list2):
        return 1
    else:
        return 2

比较每一轮:

list1 = [30, 50, 10, 80, 100, 40]
list2 = [60, 20, 10, 20, 30, 20]

def winner_round(list1,list2):
    if len(list1) != len(list2): return -1
    score1, score2 = 0
    for i in range(list1):
        if list1[i] > list2[i]:
            score1 +=1
        else:
            score2 +=1
    if score1 > score2:
        return 1
    else:
        return 2
于 2020-10-03T20:26:00.223 回答
0

这将是我对您的问题的解决方案:

    def get_points(teamA,teamB):
    if len(teamA)!=len(teamB):
        print("Both lists have to be of same length.")
        return -1
    points=0
    for i in range(len(teamA)):
        if teamA[i]>teamB[i]:
            points+=1

    print("points:",points)
    return points

我首先检查了两个列表是否具有相同的长度,然后遍历两个列表,如果一个大于另一个,则增加一个计数器。(顺便说一句,你试图在 return 语句之后打印一些东西,它存在函数)希望它有所帮助,拉斯

于 2020-10-03T20:33:39.293 回答
0

如果每个项目大于另一个,则将每个项目逐一比较,然后加 1point

list1 = [30, 50, 10, 80, 100, 40]
list2 = [60, 20, 10, 20, 30, 20]

def winner_round(list1,list2):
  point = 0

  if len(list1)!=len(list2):
    return -1

  for i in range(len(list1)):
      if list1[i] > list2[i]:
          point+=1
  return point
于 2020-10-03T20:31:14.267 回答