python 递归函数 内存底层_python - 对递归函数的后续问题,该函数解决了在游戏中达到一定数量点数的所有可能方法 - 堆栈内存溢出...

原始问题(已解决):假设您可以简化足球计分系统,您可以得到{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.当我从追加切换到仅向列表添加值时,分数变量的行为为什么会改变?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值