简体   繁体   English

当执行Sympify时,将切换表达式的顺序(Python的Sympy)

[英]When Sympify is executed, the order of expressions is switched (Python's Sympy)

I ran the following program 我运行了以下程序

from sympy import *

str = "Abs(a)*(β-α)**3/6"
print(str)
print(sympify(str))

The execution result was as follows. 执行结果如下。

Abs(a)*(β-α)**3/6
(-α + β)**3*Abs(a)/6

As a result of executing sympify , the order of the expressions has changed. 由于执行sympify ,表达式的顺序已更改。

I want to match the execution results as follows. 我要匹配执行结果,如下所示。

Abs(a)*(β-α)**3/6
Abs(a)*(β-α)**3/6

What should I do? 我该怎么办?


The reason why I want to do this is that I don't want to make it look weird when converting an expression to mathml format. 我要这样做的原因是,我不想在将表达式转换为mathml格式时使它看起来很奇怪。

str = "Abs(a)*(β-α)**3/6"
print(mathml(sympify(str),printer='presentation'))

When the above program is executed, the following is output. 执行上述程序时,将输出以下内容。

<mrow><mfrac><mrow><msup><mfenced><mrow><mrow><mo>-</mo><mi>&#945;</mi></mrow><mo>+</mo><mi>&#946;</mi></mrow></mfenced><mn>3</mn></msup><mo>&InvisibleTimes;</mo><mrow><mfenced clos
e="|" open="|"><mi>a</mi></mfenced></mrow></mrow><mn>6</mn></mfrac></mrow>

It looks like the image below. 如下图所示。

在此处输入图片说明

I want the formula to look like the image below. 我希望公式看起来像下面的图像。

在此处输入图片说明

If you apply the following diff to SymPy, I think your case will work: 如果您将以下差异应用于SymPy,我认为您的案例会起作用:

diff --git a/sympy/printing/str.py b/sympy/printing/str.py
index ee560ca..cb0db5e 100644
--- a/sympy/printing/str.py
+++ b/sympy/printing/str.py
@@ -51,6 +51,8 @@ def _print_Add(self, expr, order=None):

         PREC = precedence(expr)
         l = []
+        if len(terms) == 2 and str(terms[0])[0] == '-' and str(terms[1])[0] != '-':
+            terms.reverse()
         for term in terms:
             t = self._print(term)
             if t.startswith('-'):

(It prints b - a as the same instead of as -a + b with that change.) (它打印出的b - a相同,而不是-a + b 。)

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

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