3

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
ms8
  • 417
  • 2
  • 13

3 Answers3

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)
Community
  • 1
  • 1
George Hanna
  • 382
  • 2
  • 15
2

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)
sgp
  • 1,738
  • 6
  • 17
  • 31
0

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
Bi Rico
  • 25,283
  • 3
  • 52
  • 75