原始问题(已解决):假设您可以简化足球计分系统,您可以得到{2,3,7}分,那么给定多个分数,您可以使用哪些可行的方法?
在此链接到该问题
我试图绕过这些递归函数在下面的代码中维护得分和结果变量的方式。
代码解决方案(由ggorlen撰写):
def find_scoring(points, ways_to_score=[2, 3, 7]):
def score_finder(points, scores, result):
if points == 0:
result.append(scores[:])
elif points > 0:
for val in ways_to_score:
scores.append(val)
score_finder(points - val, scores, result)
scores.pop()
return result
return score_finder(points, [], [])
这很漂亮,并且完全回答了我的原始问题。 但是,在阅读了《编程面试要素》(Python)中的一些问题之后,我决定尝试传递结果和分数列表的方式。 我模拟了作者的一种技术,即每次递归调用该函数时都不会传递结果列表,而是分配空列表的默认值:
def find_scoring2(points, ways_to_score=[2, 3, 7]):
def score_finder(points, scores, result = []):
if points == 0:
result.append(scores[:])
elif points > 0:
for val in ways_to_score:
scores.append(val)
score_finder(points - val, scores)
scores.pop()
return result
return score_finder(points, [])
这产生了相同的结果,其思想来自EPI第235页(生成平衡的括号)。
然后,我决定更改scores变量的创建方式,以摆脱从列表中弹出的需求。 我不懂代码,但我还是从同一本书中复制了这个想法。
def find_scoring3(points, ways_to_score=[2, 3, 7]):
def score_finder(points, scores, result = []):
if points == 0:
result.append(scores[:])
elif points > 0:
for val in ways_to_score:
#scores.append(val)
score_finder(points - val, scores + [val])
#scores.pop()
return result
return score_finder(points, [])
因此,我的问题是:1.如何围绕每次都设置为空列表的结果变量,仍然产生正确的解决方案? 是否有一些视频或参考资料可以帮助我了解其工作原理? 2.当我从追加切换到仅向列表添加值时,分数变量的行为为什么会改变?