python - 从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
。提前致谢
解决方案
已经没有此功能,但您可以像这样制作:
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]]
推荐阅读
- java - 更改克隆数组的值时,更改源数组值
- javascript - 如何使socket.io异步方法同步?
- java - Java JMX RMI Accessible with Common Credentials 所需的解决方案(未经身份验证的检查)
- javascript - 如何使用谷歌图表创建蝴蝶(发散)图表
- lua - How to make this Logitech Mouse LUA script work better?
- sql - 如何在 T-SQL 中使用递归 CTE 获得完整的层次结构?
- flutter - Flutter:小部件不是“ObstructingPreferredSizeWidget”类型的子类型
- powershell - Powershell Invoke-WebRequest 在下载失败时会抛出错误吗?
- mysql - mysql过程参数和FIND_IN_SET性能
- python - 没有标准偏差值的范围内的 Numpy 正态分布