問題如下:每場比賽有兩支隊伍參賽。在所有這些比賽中將有一名獲勝者和一名失敗者,并且沒有平局。每個團隊將與所有其他團隊競爭一次。球隊每贏一場得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。有人可以指導我完成這個嗎?
uj5u.com熱心網友回復:
您忘記了一個索引,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#
在任何平局中,結果只會顯示第一支球隊擁有該分數 - 你可以解決這個問題,但任務并沒有告訴你這樣不需要。
uj5u.com熱心網友回復:
您的違規線路位于
competitions[i][0] = 3
在哪里修改比賽而不是記分牌,然后你應該在哪里
d[competitions[i][0]] = 3
我提出以下可能更容易理解來計算整個記分牌的方法:
- 顯式變數
- 邊緣情況處理(記分牌中缺少團隊)。
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],
)
請注意,至少一次未獲勝的球隊將不會出現在記分牌中。也許我們也想擁有它們,對此有不同的解決方案,但是由于您似乎只想要贏家,所以我沒有添加。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/465156.html
