def simulate_tournament(teams):
if len(teams) == 1:
return teams[0]['team']
else:
teams = simulate_round(teams)
simulate_tournament(teams)
return teams[0]['team']
return teams[0]['team']
如果没有if-else语句之外的最后一行,我的代码将无法运行。但我不明白为什么我需要这个?函数是否会迭代到len(teams) == 1
,从而返回团队?
由于您的else块没有return
语句或任何对象来保存数据,对于递归调用,它正在调用并返回Nothing,因此您没有得到任何结果
def simulate_tournament(teams):
if len(teams) == 1:
result= teams[0]['team']
else:
teams = simulate_round(teams)
result = simulate_tournament(teams)
return result
您需要返回teams[0]["teams"],因为递归需要知道上一个输出,这样它才能成为下一个输入。尝试追踪返回变量是下一个输入的代码流。理想情况下,您应该返回simulate_turnation(teams(。本指南可能有助于:https://www.programiz.com/python-programming/recursion
我正在对您没有解释的函数进行假设。
simulate_round(teams)
获取一个团队列表,并将其减少一半simulate_tournament(teams)
是锦标赛的实际运行
我认为在这种情况下,锦标赛更像是一个回合的超集,你没有多个锦标赛,但你有多个回合。有了这些假设,这就是我提出的解决方案。
def simulate_tournament(teams):
while len(teams) > 1:
teams = simulate_round(teams) # Run the round, returning all the winners
if not teams:
return None # If we ran a round and NOBODY won, the result is None
return teams[0]['team'] # This means there was exactly 1 winner, so return that