Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I turn this for loop into recursion or dynamic programming?

I am trying to make the code that I have into either recursion or dynamic programming.

    import numpy as np

    index_list = [1, 2, 0]
    weights = [0.3, 0.8]
    A_matrix = np.asarray([[0, 1, 2], [0, 1, 2], [0, 1, 2]])
    initial_best_vector = A_matrix[:, 1]

    # set best_vector_combinations to initial_best_vector
    best_vector_combinations = initial_best_vector
    for index, _ in enumerate(index_list[1:]):
        best_vector_combinations = (
            1 - weights[index]
        ) * best_vector_combinations + (
            weights[index] * A_matrix[:, index_list[index + 1]]
        )

Is it possible to do so? What I am doing is a nested linear combination of vectors, with the initial base being the initial_best_vector, which corresponds to the index_list.

In other words, let c_i be the columns of the matrix A, I want:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

((1-0.3) * c_1 + 0.3 * c_2) * (1-0.8) + 0.8 * c_0

I hope to make this case more general to hold for any length of numbers.

>Solution :

If you want a recursive implementation, if would be helpful to start with a simpler example and figure out the recurrence relation.
Let vectors = [8,5,2,1] (1D array for simplicity) and let weights = [0.5, 0.8, 0.1, 0.2].

First step of computation: (8 * 0.5) + (1-0.5)*(result of second step).
Second step: 5 * 0.8 + (1-0.8)*(result of third step).

You can work this out further, but the basic relation is

result(vectors, weights) = 
(
    vectors[0]*weights[0]) + 
    (1-weights[0]) * (result(vectors[1:], weights[1:]))
) if (vectors and weights) else 0

Implementation:

def calculate(vectors, weights):
    if not (vectors or weights):
        return 0
    if not weights:
        return vectors[0]
    return vectors[0]*weights[0] + (1-weights[0]) * (result(vectors[1:], weights[1:]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading