[英]How to find sum of recursion result
First write a function called rec_dig_sum
that takes in an integer and returns the recursive digit sum of that number.首先编写一个名为rec_dig_sum
的 function ,它接收一个 integer 并返回该数字的递归数字总和。
Examples of recursive digit sums:递归数字和的示例:
101 => 1+0+1 = 2
191 => 1+9+1 = 11 => 1+1 = 2
5697 => 5+6+9+7 = 27 => 2+7 = 9
Then use that function within another function called distr_of_rec_digit_sums
, that returns a dictionary where the keys are recursive digit sums, and the values are the counts of those digit sums occurring between a low and high (inclusive) range of input numbers.然后在另一个名为distr_of_rec_digit_sums
的 function 中使用 function ,它返回一个字典,其中键是递归数字和,值是出现在低位和高位(含)之间的那些数字和的计数。 Assume low and high are positive integers where high is greater than low, and neither low nor high are negative.假设 low 和 high 是正整数,其中 high 大于 low,并且 low 和 high 都不是负数。
I have this as the first part:我有这个作为第一部分:
def rec_dig_sum(n):
total = 0
for i in str(n):
total += int(i)
return total
It bothers me that the OP's recursive solution, and the other solutions presented here, have a for
loop in the middle of them!令我困扰的是,OP 的递归解决方案以及此处介绍的其他解决方案中间有一个for
循环! Let's go fully (doubly) recursive on this problem!让我们 go完全(双重)递归解决这个问题! And since it's a number problem, let's also toss that str()
function everyone else is using:既然这是一个数字问题,我们也抛开其他人都在使用的str()
function :
def rec_dig_sum(number):
if number < 10:
return number
quotient, remainder = divmod(number, 10)
return rec_dig_sum(rec_dig_sum(quotient) + remainder)
print(rec_dig_sum(101))
print(rec_dig_sum(191))
print(rec_dig_sum(5697))
OUTPUT OUTPUT
> python3 test.py
2
2
9
>
My example solution for the second function is conventional, but one of my few opportunites to use the dict.fromkeys()
method:我的第二个 function 的示例解决方案是传统的,但是我使用dict.fromkeys()
方法的少数机会之一:
def distr_of_rec_digit_sums(low=0, high=1500):
histogram = dict.fromkeys(range(10), 0)
for number in range(low, high + 1): # a low and high (inclusive) range
histogram[rec_dig_sum(number)] += 1
return histogram
print(distr_of_rec_digit_sums(0, 1500))
OUTPUT OUTPUT
> python3 test.py
{0: 1, 1: 167, 2: 167, 3: 167, 4: 167, 5: 167, 6: 167, 7: 166, 8: 166, 9: 166}
>
So for both parts of your question.因此,对于您问题的两个部分。
First, the recursive function:一、递归function:
def recursive_digits(n):
total = sum([int(i) for i in str(n)])
if total < 10:
return total
else:
return recursive_digits(total)
Then you use it in the other function:然后你在另一个function中使用它:
def distr_of_rec_digit_sums(low, high):
digits = {item : 0 for item in range(10)}
for i in range(low, high+1):
digits[recursive_digits(i)] += 1
return digits
And since the function name starts with 'distr', I guess, someone is interested in the distribution in digit sums.而且由于 function 名称以“distr”开头,我猜有人对数字总和的分布感兴趣。 It is surprisingly (or unsurprisingly) uniform.它出人意料地(或不出所料地)统一。 This is for the range in your question (0 - 1500).这是针对您问题的范围(0 - 1500)。
You are almost there你快到了
def rec_dig_sum(n):
total = 0
for i in str(n):
total += int(i)
return str(total)
t = "5697"
while len(t) != 1:
t = rec_dig_sum(t)
print (t)
We need a condition to break out of recursion, for this case we want to stop when the number of digits is 1 ie we will break if len(n) === 1
.我们需要一个条件来中断递归,对于这种情况,我们希望在位数为 1 时停止,即如果len(n) === 1
则我们将中断。
If not we calculate the current sum and and again start.如果不是,我们计算当前总和并重新开始。
def rec_dig_sum(n):
if len(n) == 1:
return int(n)
total = 0
for i in str(n):
total += int(i)
return rec_dig_sum(str(total))
rec_dig_sum(str(5697))
If you are learning recursion and facing difficulty, start by writing the same using loops (non-recursive) and then try to make it recursive by targeting to remove the loop.如果您正在学习递归并面临困难,请首先使用循环(非递归)编写相同的内容,然后尝试通过删除循环来使其递归。
It looks like a recursive solution would fit better, such as:看起来递归解决方案更适合,例如:
def rec_dig_sum(n):
if n < 0:
raise Exception('the arg must be positive')
# Stop condition: single number
if n < 10:
return n
else:
# Convert n into a str and each number back into int to be added
total = sum(map(int, str(n)))
return rec_dig_sum(total)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.