gpt4 book ai didi

python - 使用递归替换 goto

转载 作者:行者123 更新时间:2023-12-01 05:16:53 27 4
gpt4 key购买 nike

我有一个简单的数字根计算(即将整数中的所有数字相加,如果总数超过一位数字,则重复该过程,直到最终得到一位数字的答案)。

我的第一个冲动是简单地计算初始字符串中的数字之和,测试结果是否多于一位数字,如果是,则转到求和套件的开头:

例如。

line = "123456789"
sum_digits = 0
# label: if I could use goto, it would go to here!
n_chars = len(line)
while n_chars > 0:
sum_digits = sum_digits + int(line[0])
line = line[1:]
n_chars -= 1
line = str(sum_digits)
if len(line) < 2: # all done
print("digital root is ", sum_digits);
else:
goto label: # need to repeat until get single digit root number

但是,当然,Python 不支持“goto”——所以我想这应该写成一个递归函数?编写此代码的最简洁方法是什么?

ps。我试图让代码非常简单易懂/解释,因为我正在与正在学习编程的儿子进行编码练习

最佳答案

要替换 goto,其想法是在每次迭代找到总和后跟踪该行的内容。

所以,如果我理解你的问题,以下应该有效:

def find_root(line):
while len(line) > 1:
sum_digits = 0
for num in list(line):
sum_digits += int(num)
line = str(sum_digits)
print line


>>find_root("123456789")
9
>>find_root("93856")
4

关于python - 使用递归替换 goto,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23002680/

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