首页 > 解决方案 > 从simpy中的线性组合生成列表

问题描述

我正在使用 sympy 进行一些计算,但我需要使用我必须定义的规则来操纵乘法的结果。让我们假设我有

a, b, c, d = symbols('a b c d', commutative=False)
res = a*b + b*c + c*d

我想知道如何编写一个接受 res 并给出此类列表的函数

[[a,b],[b,c],[c,d]]

因为每次我尝试执行诸如list(res)python 之类的操作时都会抛出异常Mul (Add) object is not iterable。提前致谢

标签: pythonsympy

解决方案


已经没有此功能,但您可以像这样制作:

def factors(expr):
    result = []
    for term in Add.make_args(expr):
        flat_factors = []
        for factor in Mul.make_args(term):
            symbol, power = factor.as_base_exp()
            flat_factors += [symbol] * power
        result.append(flat_factors)
    return result

这给出了:

In [74]: factors(a*b + b*c + c*d)
Out[74]: [[a, b], [b, c], [c, d]]

In [75]: factors(a**2*b + a*b**2)
Out[75]: [[a, b, b], [a, a, b]]

推荐阅读