python - Implement recursion using one recursive call -
given function 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 implement using recursion 3 recursive calls inside 1 function. want 1 recursion call inside function. how can done ?
to implement using 3 recursive calls here 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 rule because there 3 calls recur
your attempt in right direction needs 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)
Comments
Post a Comment