1 回答

TA貢獻(xiàn)1836條經(jīng)驗 獲得超4個贊
這是一個非常符合您方法的解決方案。
將每個 Counter 轉(zhuǎn)換為向量,將不同的 ID 視為單獨的維度。
求解線性方程組。
from collections import Counter
import numpy as np
from scipy import linalg
lhs = (Counter({22.99: 1}), Counter({12.011: 2, 15.999: 2}), Counter({12.011: 7}))
rhs = Counter({12.011: 15, 15.999: 1})
# get unique keys that occur in any Counter in 2D
# each unique key represents a separate dimension
ks = np.array([*set().union(rhs, *lhs)])[:, None]
# get a helper function to convert Counters to vectors
ctr_to_vec = np.vectorize(Counter.__getitem__)
lhs_mat = ctr_to_vec(lhs, ks)
rhs_vec = ctr_to_vec(rhs, ks)
# compute coefficients solving the least-squares problem
coefs = linalg.lstsq(lhs_mat, rhs_vec)[0]
is_linear_comb = np.allclose(lhs_mat @ coefs, rhs_vec)
添加回答
舉報