Skip to content
DeepForgeby svx
All problems
MediumLinear Algebrala-296

Weighted L2 Norm

Problem

Compute the weighted L2 norm of a vector with nonnegative weights w:

||v||_w = sqrt(sum_i w[i] * v[i]^2)

Return None if any weight is negative, since the weighted quadratic form would not define a norm.

Hint

Square the entries, scale by the weights, sum, and take the square root.

Test cases

case 1
in: [[3,4],[1,1]]
expected: 5
case 2
in: [[3,4],[2,0.5]]
expected: 5.0990195135927845
case 3
in: [[3,4],[0,0]]
expected: 0
case 4
in: [[1,0],[-1,1]]
expected: null
case 5
in: [[1,2,2],[4,1,1]]
expected: 3.4641016151377544
Starter codePython
def weighted_l2_norm(v, w):
    # Your code here
    pass

5 test cases · run your code against them in the editor