我编写了用于循环迭代的python,如下所示。我想知道是否有可能将其转换为递归函数。
a = int(input("Please enter the first number: ")) 
b = int(input("Please enter the second number: ")) 
res = 0  
for i in range(a,b+1):
    temp = 1  
    for j in range(1,i+1):         
        temp = temp * j      
        res = res + temp      
print("Sum of products from 1 to each integer in the range ",a," to ",b," is: ",res) 我期待下面的例子:
def recursion(a,b):
res = 0 
   if condition or a while condtion
    ....
       return ....
   a = int(input("Please enter the first number: "))   
   b = int(input("Please enter the second number: ")) 
  print("Sum of products from 1 to each integer in the range ",a," to ",b," is: ",res) 知道吗?
发布于 2022-12-02 00:55:29
a = int(input("Please enter the first number: ")) 
b = int(input("Please enter the second number: ")) 
res = sum([x for x in range(int(a), int(b)+1)])
print(res)我的问题是,为什么您需要它是递归的?我之所以这么问,是因为这个特别的答案似乎不是通过递归来处理的。
如果需要使用递归
def recursive_sum(m,n):
    if n <= m:
        return n
    else:
        return n+recursive_sum(m, n-1)编辑:
提出的问题包括范围的阶乘之和,对只包括和部分表示歉意。
def factorial(b):
    if (b==1 or b==0):
        return 1
    else:
        return (b * factorial(b - 1))
res = sum(map(factorial, range(a,b+1)))您要将范围内的每个值乘以前面和求和的乘积的原始代码。
例如,问题书写方式的范围(5,10)总计为4500198,其中阶乘和= 4037880。
如果你只为值5打印出来,你就会得到1+3+9+33+153 where !5=120,这就是你想要完成的吗?
发布于 2022-12-02 00:12:31
可能是这样的,想象一下把问题分成更小的子问题。
def recursive_sum(a, b, res=0):
    if a > b:
        return res
    temp = 1
    for j in range(1, a+1):
        temp = temp * j
        res = res + temp
    return recursive_sum(a+1, b, res)
a = int(input("Please enter the first number: ")) 
b = int(input("Please enter the second number: ")) 
res = recursive_sum(a, b)
print(f"Sum of products from 1 to each integer in the range {a} to {b} is: {res}") https://stackoverflow.com/questions/74649471
复制相似问题