I have an issue with defining this function recursively. My goal is for the function to return the maximal income from a given n. n (in meters) here is the amount of cloth. The h list is the profit when selling a rug that is n meters long. For example, h[2]=5 is the profit when making a 2 meters long carpet which is for simplicity 5 dollars, and h[0]=0 since no cloth is available and no product produced. So the h list is just the market value of rugs of different lengths. I want the function to return the maximum profit if I have n meters of cloth. The prices are only defined for carpets up to 4 m, hence why the h list is what it is. The recursion for n=2 for example calculates the value of making a rug 2 m big and compares the profit with making two 1 m carpets and so on.
The recursion is loosely stated as:
income(0) = 0income(n) = max(h[i]+income(n-i))for1<=i<=n
As of now, by the code below, I'm getting a recursion limit exceeded. Which I don't find weird as I have no condition for limiting the loop but the issue is I don't know how to proceed and define some sort of constraint. I realize the description here might be very confusing but please ask and I'll try to explain more extensively.
def income(n):
h = [0,2,5,6,9]
for i in range(n):
return max(h[i]+income(n-i))
EDIT: This is my solution I came up with.
def income(n):
"""Returns maximum profit by a given n."""
h = [2,5,6,9,0]
m = []
if n == 0:
return 0
else:
for i in range(n):
m.append(h[i]+income(n-i-1))
return max(m)
With cache:
def memoize(f):
memo = {}
def helper(x):
if x not in memo:
memo[x] = f(x)
return memo[x]
return helper
income = memoize(income)
income(0) = 0. The first thing every recursive function should do is to check for the recursion termination condition.max(h[i]+income(n-i) for i in range(1, n+1)); read about list comprehensions and generator expressions to understand this.