首页 文章

Python中计数器的线性组合

提问于
浏览
0

我有一些像下面的Counter对象代表方程式的左侧和右侧:

左手边: (Counter({22.99: 1}), Counter({12.011: 2, 15.999: 2}), Counter({12.011: 7}))

右手边: Counter({12.011: 15, 15.999: 1})

我的目标是找到等式两边的共同元素,然后确定左边的线性组合,这可以给我正确的一面 .

在上面的例子中,要解决的等式将是:

2A*12.011 + 7B*12.011 = 15W*12.011

2A*15.999 = W*15.999

我预计这个操作将涉及将Counter字典转换为矩阵以解决线性方程组,但我仍然坚持如何做到这一点 .

1 回答

  • 1

    这是一个非常符合您的方法的解决方案 .

    • 将每个计数器转换为向量,将不同的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)
    

相关问题