Skip to content Skip to sidebar Skip to footer

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 func

Solution 1:

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)

Solution 2:

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)

Solution 3:

At first glance, this looks like a dynamic programming problem. I really like memoization for problems like this because it keeps the code nice and readable, but also gives very good performance. Using python3.2+ you could do something like this (you can do the same thing with older python versions but you'll need to either implement your own lru_cache or install one of the many 3rd party that have similar tools):

import functools

@functools.lru_cache(128)
def recur(n):
  print("computing recur for {}".format(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)

Notice that the function only gets called once per n:

recur(6)
# computing recur for 6
# computing recur for 5
# computing recur for 4
# computing recur for 3
# computing recur for 1
# computing recur for 0
# computing recur for 2

Post a Comment for "Implement Recursion Using One Recursive Call"