问题如下:每场比赛有两支队伍参赛。所有这些比赛将有一个赢家和一个输家,没有平局。每队将与所有其他队进行一次比赛。每队每赢一场得3分,每输一场得0分。保证比赛至少有两支队伍,并且只有一名冠军。
我们有两个输入,竞赛数组和结果数组。我们需要编写一个函数来返回锦标赛的获胜者,或者更具体地说,返回得分最多的球队的名称。我们有两个字符串:第一个是主队的名字,第二个是客场球队的名字。结果数组表示这些比赛的获胜者。在结果数组中,1表示主队获胜,0表示客队获胜。结果数组与竞赛数组长度相同,结果数组中的索引与竞赛数组中的索引相对应。
def tournamentWinner(competitions, results):
# Write your code here.
d = {}
for i in range(len(results)):
if results[i] == 0:
if competitions[i][1] not in d:
d[competitions[i][1]] = 3
else:
d[competitions[i][1]] += 3
elif results[i] == 1:
if competitions[i][0] not in d:
competitions[i][0] = 3
else:
d[competitions[i][0]] += 3
print(max(d,key=d.get))
tournamentWinner([
["HTML", "Java"],
["Java", "Python"],
["Python", "HTML"],
["C#", "Python"],
["Java", "C#"],
["C#", "HTML"]
],[0, 1, 1, 1, 0, 1])
输出应该是c#,但我得到Java作为我的代码。有人能给我指点一下吗?
您忘记了d
的一个索引,因此您的字典中永远不会添加主场胜利:
def tournamentWinner(competitions, results): d = {} for i in range(len(results)): if results[i] == 0: if competitions[i][1] not in d: d[competitions[i][1]] = 3 else: d[competitions[i][1]] += 3 elif results[i] == 1: if competitions[i][0] not in d: competitions[i][0] = 3 # HERE missing d[...] = 3 else: d[competitions[i][0]] += 3 print(d) # => {'Java': 6, 'C#': 6} - theres smth missing ;) print(max(d,key=d.get))
在返回结果之前,可以通过步进或打印出d
来轻松查看。
你可以简化它(改变为返回结果而不是打印):
def tournamentWinner(competitions, results):
d = {}
for teams,result in zip(competitions,results):
# teams is a list of 2 elements, result is 0 or 1:
# the winner is the index into the 2-elem-list by 1-result
winner = teams[1-result] # [home,far], 1 == home wins
d.setdefault(winner,0) # create key with 0 if not there
d[winner] += 1 # no need to add up 3 - the points are never used
print(d) # ==> {'Java': 2, 'Python': 1, 'C#': 3}
return max(d.items(), key=lambda tup:tup[1]) [0] # select the key
result = tournamentWinner([
["HTML", "Java"],
["Java", "Python"],
["Python", "HTML"],
["C#", "Python"],
["Java", "C#"],
["C#", "HTML"]
],[0, 1, 1, 1, 0, 1])
print(result)
输出C#
在任何平局时,结果将只显示拥有该分数的第一支球队-您可以解决这个问题,但任务没有告诉您这样做,因此不需要
你的错误行在
competitions[i][0] = 3
,你修改比赛,而不是记分牌,在那里你应该有
d[competitions[i][0]] = 3
我的建议如下,这可能更容易理解计算整个计分板:
<<ul>def get_winner_in_score_board(score_board):
return max(score_board, key=score_board.get)
def tournament_winner(competitions, results):
score_board = {}
for competitors, result in zip(competitions, results):
if result == 1:
loser = competitors[1]
winner = competitors[0]
else:
loser = competitors[0]
winner = competitors[1]
try:
score_board[winner] += 3
except KeyError:
score_board[winner] = 3
return get_winner_in_score_board(score_board)
tournament_winner(
[
["HTML", "Java"],
["Java", "Python"],
["Python", "HTML"],
["C#", "Python"],
["Java", "C#"],
["C#", "HTML"],
],
[0, 1, 1, 1, 0, 1],
)
请注意,至少一次未获胜的队伍将不会出现在记分牌上。也许我们也想拥有它们,有不同的解决方案,但由于您似乎只想要赢家,我没有添加它。