繁体   English   中英

将Mathematica代码转换为Python

[英]Converting a Mathematica code into Python

我正在将一些代码从Mathematica转换为Python。 假设我有以下列表:

l = [["x1", "x2", "x3"], ["x4", "x5", "x6"], ["x7", "x8"], ["x9", 
"x10"], ["x11"]]

我想将其转化为多项式,以使列表中每个元素的长度成为变量x的幂。 在Mathematica中,我这样做是:

Total[x^Map[Length, l]]

这使:

Output: x + 2 x^2 + 2 x^3

这意味着列表1中有1个元素,其长度为1,2个元素的长度为2,2个元素的长度为3。在Python中,我尝试了以下操作:

sum(x**map(len(l), l))

但这不起作用,因为未定义x,我也尝试使用“ x”,它也不起作用。 我想知道如何翻译这样的代码。

您可以为此使用

import sympy as sym

l = [["x1", "x2", "x3"], ["x4", "x5", "x6"], ["x7", "x8"], ["x9", "x10"], ["x11"]]

x = sym.Symbol('x')

expr = sym.S.Zero
for exponent in map(len, l):
    expr += x ** exponent

print(expr)

会给:

2*x**3 + 2*x**2 + x

在这里,我创建了一个符号零单例sympy.S.Zero ,然后将x的凸起加到我们可以从map(len, l)获得的幂上。

print(list(map(len, l)))

会给:

[3, 3, 2, 2, 1]

这是使用sympy的另一种解决方案:

from sympy import Matrix
from sympy.abc import x

l = [["x1", "x2", "x3"], ["x4", "x5", "x6"], ["x7", "x8"], ["x9", "x10"], ["x11"]]
powers = Matrix(list(map(len, l))) # Matrix([3, 3, 2, 2, 1])
raise_x_to_power = lambda y: x**y
output = sum(powers.applyfunc(raise_x_to_power))

print(output)
# 2*x**3 + 2*x**2 + x

您可以根据自己的规范创建一个字符串,例如:

from itertools import groupby
l = [["x1", "x2", "x3"], ["x7", "x8"], ["x9", "x10"], ["x4", "x5", "x6"], ["x11"]]

g = groupby(sorted(l, key = len), key = len)

s = " + ".join([" ".join([str(len(list(i))), "* x **", str(j)]) for j, i in g])
print(s)
#output
#1 * x ** 1 + 2 * x ** 2 + 2 * x ** 3

但这只是一个字符串,而根据您的问题,我认为您想稍后评估此公式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM