这里有一个非常符合您方法的解决方案。
-
将每个计数器转换为向量,将不同的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)