首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将循环转换为递归函数

将循环转换为递归函数
EN

Stack Overflow用户
提问于 2022-12-02 00:02:54
回答 2查看 65关注 0票数 0

我编写了用于循环迭代的python,如下所示。我想知道是否有可能将其转换为递归函数。

代码语言:javascript
运行
复制
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) 

我期待下面的例子:

代码语言:javascript
运行
复制
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) 

知道吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-12-02 00:55:29

代码语言:javascript
运行
复制
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)

我的问题是,为什么您需要它是递归的?我之所以这么问,是因为这个特别的答案似乎不是通过递归来处理的。

如果需要使用递归

代码语言:javascript
运行
复制
def recursive_sum(m,n):
    if n <= m:
        return n
    else:
        return n+recursive_sum(m, n-1)

编辑:

提出的问题包括范围的阶乘之和,对只包括和部分表示歉意。

代码语言:javascript
运行
复制
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,这就是你想要完成的吗?

票数 0
EN

Stack Overflow用户

发布于 2022-12-02 00:12:31

可能是这样的,想象一下把问题分成更小的子问题。

代码语言:javascript
运行
复制
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}") 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74649471

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档