Compute the L1 norm, L2 norm, and Frobenius norm of vectors and matrices. The L1 norm is the sum of absolute values, the L2 norm is the square root of the sum of squares, and the Frobenius norm extends the L2 norm to matrices.
from typing import List, Union
def l1_norm(v: List[float]) -> float:
return sum(abs(x) for x in v)
def l2_norm(v: List[float]) -> float:
return sum(x * x for x in v) ** 0.5
def frobenius_norm(matrix: List[List[float]]) -> float:
total = 0.0
for row in matrix:
for val in row:
total += val * val
return total ** 0.5
def compute_norms(
data: Union[List[float], List[List[float]]]
) -> dict:
# Check if it's a matrix (list of lists) or vector
if isinstance(data[0], list):
flat = [val for row in data for val in row]
return {
"l1_norm": round(l1_norm(flat), 4),
"l2_norm": round(l2_norm(flat), 4),
"frobenius_norm": round(frobenius_norm(data), 4)
}
else:
return {
"l1_norm": round(l1_norm(data), 4),
"l2_norm": round(l2_norm(data), 4)
}