Let's see how we can optimize a financial portfolio using DP:
- We will use the KPDP.py file that is already provided for you as a reference. This algorithm starts with the definition of a KnapSackTable() function that will choose the optimal combination of the objects respecting the two constraints imposed by the problem: the total weight of the objects equal to 10, and the maximum value of the chosen objects, as shown in the following code:
def KnapSackTable(weight, value, P, n):T = [[0 for w in range(P + 1)]for i in range(n + 1)]
- Then, we set an iterative loop on all objects and on all weight values, as follows:
for i in range(n + 1): for w in range(P + 1): if i == 0 or w == 0: T[i][w] = 0 elif weight[i - 1] <= w: T[i][w] ...