Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement recursion using one recursive call

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 ?

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
like image 425
ms8 Avatar asked May 23 '26 20:05

ms8


2 Answers

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)
like image 186
sgp Avatar answered May 25 '26 09:05

sgp


This answer in C# may give you a hint how to do what you want.

Fibbonacci with one recursive call in Python is as follows:

def main():
  while True:
    n = input("Enter number : ")
    recur(0,1,1,int(n))

def recur(firstNum,secondNum,counter,n):
  if counter==n :
     print (firstNum)
     return
  elif counter < n
      recur (secondNum,secondNum+firstNum,counter+1,n)
like image 42
George Hanna Avatar answered May 25 '26 08:05

George Hanna