[英]Designing a recursive function that uses digit_sum to calculate sum of digits
def digit_sum(n):
if n==0 or n==1:
return n
else:
return n+digit_sum(n-1)
def digital_root(n):
if n<10:
return n
else:
return digit_sum((n // 10) + n % 10)
我试图用digit_sum
计算的数字之和digital_root
有人可以帮我请。 我正在尝试使用digital_root
的递归函数。
在Python shell中运行该文件:
digital_root(1969)
这应该计算1 + 9 + 6 + 9 = 25然后因为25大于10它应该计算其数字2 + 5的总和,以便最终答案是7。
要获得(正整数)数字的最后一位数,您可以计算模数:
last_digit = n % 10
该数字的其余部分(不包括最后一个地方)是:
rest = (n - last_digit) / 10
理论上这应该足以分割数字并添加数字:
def sum_digits(n):
if n < 10:
return n
else:
last_digit = n % 10
rest = n // 10
# or using divmod (thanks @warvariuc):
# rest, last_digit = divmod(n, 10)
return last_digit + sum_digits(rest)
sum_digits(1969) # 25
如果你想要递归地应用这个值,直到你有一个小于10的值,你只需要调用这个函数,只要不满足该条件:
def sum_sum_digit(n):
sum_ = sum_digit(n)
if sum_ < 10:
return sum_
else:
return sum_sum_digit(sum_)
sum_sum_digit(1969) # 7
如果您有兴趣另一种计算数字总和的方法是将数字转换为字符串,然后添加字符串的每个字符:
def sum_digit(n):
return sum(map(int, str(n)))
# or as generator expression:
# return sum(int(digit) for digit in str(n))
如果你真的需要一个递归解决方案而不使用任何循环( for
, while
),那么你总是可以再次递归以确保一个数字:
def digital_root(n):
if n < 10:
return n
a, b = divmod(n, 10)
b += digital_root(a)
return digital_root(b)
>>> digital_root(1969)
7
或者你可能根本就没有递归:
def digital_root(n): # n > 0
return 1+(n-1)%9
>>> digital_root(1969)
7
尝试这个...
digitSum = 0
solution = 0
S = raw_input()
S = list(map(int, S.split()))
#print S
for i in S:
digitSum += i
#print digitSum
singleDigit = len(str(digitSum)) == 1
if singleDigit == True: solution = digitSum
while singleDigit == False:
solution = sum( [ int(str(digitSum)[i]) for i in range( 0, len(str(digitSum))) ] )
digitSum = solution
singleDigit = len(str(solution)) == 1
print(solution)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.