gpt4 book ai didi

Python:递归生成器

转载 作者:行者123 更新时间:2023-12-03 23:58:33 26 4
gpt4 key购买 nike

我想递归生成一串数字切片的所有可能总和。例如:

Input: '891'
Output: 18, 99, 90, 891

In details:
8+9+1 = 18
8+91 = 99
89+1 = 90
891 = 891
但是,我编写的代码产生了生成器的生成器:
# s: string of digits, c: sum of slices
def rec(s,c):
for i in range(1,len(s)+1):
if s=='': yield c
else: yield rec(s[i:],c+int(s[:i]))
我该如何解决?

最佳答案

有时很难做到正确。但是您通过添加额外的参数来混淆自己:

def rec(s):
# No split.
yield int(s)

# Split.
for i in range(1, len(s)):
left = int(s[:i])
for right in rec(s[i:]):
yield left + right
确实:
>>> list(rec("891"))
[891, 99, 18, 90]

关于Python:递归生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66277902/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com