我编写了用于循环迭代的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: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
复制相似问题