首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
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

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
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74649471

复制
相关文章

相似问题

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