Home > Mobile >  Rewrite recursion function without using recursion
Rewrite recursion function without using recursion

Time:12-14

I'm currently working on a function which is pretty easy with recursion. But I have the problem that I'm always getting an error because the function gets called to often. So I have to rewrite this function so that no recursion is used. This is the function with recursion:

def calculate_stock(stock, stock_base_line, days):
    sales_after_stock = stock - (stock_base_line/14)
    if sales_after_stock > 0:
        days  =1
        return calculate_stock(sales_after_stock, stock_base_line, days)        
    else:
        return days 

The loop should stop when sales_after_stock is lower than 0.

Now I tried to rewrite the recursion:

def calculate_stock(stock, stock_base_line, days):
    sales_after_stock = stock - (stock_base_line/14)     
    while(sales_after_stock > 0):
        if sales_after_stock > 0:
            days  =1
            sales_after_stock = sales_after_stock - (stock_base_line/14)                   
        else:
            return days
    else:
        return days

So it does not properly subtract the value of sales_after_stock and thus the loop is infinite. How can I solve this?

CodePudding user response:

There are a couple of issues with you implementation:

  • You do not need to check if sales_after_stock > 0 within the while loop, as this is checked before each iteration of the loop.
  • You are not subtracting anything from sales_after_stock - each time you always set it equal to stock - stock_base_line / 14

This should work for you:

def calculate_stock(stock, stock_base_line, days):

    sales_after_stock = stock - stock_base_line / 14
    while sales_after_stock > 0:
        days  = 1
        sales_after_stock -= stock_base_line / 14

    return days
  • Related