Home > Software design >  I require converting this for loop into a recursion function
I require converting this for loop into a recursion function

Time:12-05

rate, cashflows = 0.05,[-1100,300,450,800]

def npv_for_loop(rate,cashflows):
  NPV=0
  for i in range(len(cashflows)):
    NPV =cashflows[i]/(1 rate)**i
    print(round(NPV,3))

i generally have no idea how a recursion works and would really appreciate if anybody can help me.

CodePudding user response:

Here is an example of how you could convert the given for loop into a recursive function:

def npv(rate, cashflows, i=0, NPV=0):
    # Stop the recursion when we reach the end of the cash flows
    if i == len(cashflows):
        return NPV

    # Compute the present value of the ith cash flow
    present_value = cashflows[i] / (1   rate) ** i

    # Recursively call the function to compute the present value of the remaining cash flows
    return npv(rate, cashflows, i   1, NPV   present_value)

rate, cashflows = 0.05,[-1100,300,450,800]

# Compute the NPV of the cash flows using the recursive function
npv = npv(rate, cashflows)
print(npv)

In this code, the npv() function computes the present value of each cash flow in the given cashflows array and sums them up to compute the NPV of the cash flows. The i parameter is the index of the current cash flow being considered, and the NPV parameter is the running total of the present values of the cash flows that have been considered so far. The npv() function calls itself recursively with an updated value of i and NPV until all of the cash flows have been considered.

Recursive functions work by calling themselves with updated values for their parameters, and then using the updated values to compute a result. In the case of the npv() function, it calls itself with an updated value of i and NPV until all of the cash flows have been considered, and then it returns the final value of NPV as the result. This is an example of a tail-recursive function, where the final result is computed by the base case (i.e., when i == len(cashflows)) and then passed back up the recursive calls.

CodePudding user response:

Recursion function is a function calling itself. It works by changing the parameters each time it calls itself until some condition accruing and then it returns. When the function hit the return value it goes back to the last line called it and continue to execute from that line, just like main function calling other. When its done executing, or hit a return, it goes back to the last line called it and continues.. so on until the function ends and returns to main.

rate, cashflows = 0.05,[-1100,300,450,800]

def npv_for_loop(rate,cashflows):
  NPV=0
  npv_rec(rate, cashflows, NPV)
    
def npv_rec(rate, cashflows, npv, i=0):
    if len(cashflows) == i:
        return
    npv =cashflows[i]/(1 rate)**i
    print(round(npv,3))
    npv_rec(rate, cashflows, npv, i   1)
    
npv_for_loop(rate, cashflows)
  • Related