【发布时间】:2014-06-08 07:37:45
【问题描述】:
我有一个简单的数字根计算(即,将所有数字相加为一个整数,如果总数超过一位,请重复该过程,直到得到一个数字的答案)。
我的第一个冲动是简单地计算初始字符串中数字的总和,测试结果是否超过一位,如果是,则转到求和套件的开头:
例如。
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。我正在尝试使代码非常易于理解/解释,因为我正在与正在学习编程的儿子进行编码练习
【问题讨论】: