使用一次递归调用实现递归

编程入门 行业动态 更新时间:2024-10-23 05:39:46
本文介绍了使用一次递归调用实现递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给定如下函数:f(n) = f(n-1) + f(n-3) + f(n-4)

Given a function as follow : f(n) = f(n-1) + f(n-3) + f(n-4)

f(0) = 1 f(1) = 2 f(2) = 3 f(3) = 4

我知道在一个函数内使用三个递归调用来实现它.但我只想在函数内部进行一次递归调用.怎么做?

I know to implement it using recursion with three recursive calls inside one function. But I want to do it with only one recursion call inside the function. How it can be done ?

要使用 3 个递归调用来实现,这是我的代码:

To implement using 3 recursive calls here is my code :

def recur(n): if n == 0: return 1 elif n == 1: return 2 elif n == 2: return 3 elif n == 3: return 4 else: return recur(n-1) + recur(n-3) + recur(n-4) #this breaks the rule because there are 3 calls to recur

推荐答案

您的尝试方向正确,但需要稍作改动:

Your attempt is in the right direction but it needs a slight change:

def main(): while True: n = input("Enter number : ") recur(1,2,3,4,1,int(n)) def recur(firstNum,secondNum,thirdNum,fourthNum,counter,n): if counter==n: print (firstNum) return elif counter < n: recur (secondNum,thirdNum,fourthNum,firstNum+secondNum+fourthNum,counter+1,n)

更多推荐

使用一次递归调用实现递归

本文发布于:2023-11-30 20:34:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651402.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!