[Python] Logic Puzzle: Normalize elements of array with minimum and maximum constraints

Discussão em 'Python' iniciado por Stack, Janeiro 23, 2025.

  1. Stack

    Stack Membro Participativo

    The sum of the elements of an array needs to be one while the elements adhere to certain maximum and minimum constraints. If the element is smaller than the minimum allowed value, it element may be set to zero.

    For example, if the input array (shown in python )

    arr = np.array([0.1 , 0.1 , 0.8 , 0.01])
    max_value = 0.5
    min_value = 0.1


    Then some approach may say:

    // enforce minimum constraints
    arr = np.where(arr < min_value, 0.0, arr) // arr = [0.1, 0.1, 0.8 , 0.0]
    // enforce maximum constraints
    arr = np.where(arr > max_value, max_value, arr) // arr = [0.1, 0.1, 0.5 , 0.0]
    //normalize so sum == 1
    arr \= arr.sum() // arr = [0.14285714, 0.14285714, 0.71428571, 0.] -- violating max constraint


    I've tried many approaches for this problem. I've tried to split the cases where the sum > 1 and sum < 0. If it is larger than one, I tried to subtract the excess from other weights, but ensuring the minimum constraints hold becomes a problem, even with some proportional subtraction. Same for adding to the weights until the sum is 1 , the maximum constraints are a problem. The sum of elements must be == 1. The maximum constraint will always ensure a sum of 1 is possible. max_value < 1/len(arr)

    Another approach can be to conditionally scale the elements based on some factor of the constraints.

    Continue reading...

Compartilhe esta Página