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

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

It only gives 1 as output..:/. Reason being 1 is always then then any n so it will always display 1
@python_slayer Oops. Check the edit. Is it fine now?
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)

3 Comments

I did something like that but getting 14 for n=5 . Here is my code :ideone.com/8zk4kI
I dont want fibonacci number. Please see problem :/
Ohh I am so sorry, I misunderstood.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.