英文:
Write polynomial as word using SymPy
问题
我想输入一个多项式,并将多项式的输出以“单词”的形式写出(即在自由代数的意义上,其中所有的幂都折叠成变量的乘积)。例如,
-
输入 x**2,输出 x*x
-
输入 (xy**2)**3,输出 xyyxyyxy*y
如果有人知道如何做到这一点,将不胜感激(我是Python的初学者)。谢谢!
我查看了 SymPy 的 expand 函数,在第二个例子中给出了输出:
xy**2xy**2x*y**2。
但是这仍然没有完全简化,这与第一个例子的问题相同。我认为使用循环来将幂运算符 ** 替换为相应数量的乘法应该可以解决,但我不确定如何实现这一点。
英文:
I'd like to input a polynomial and have an output of the polynomial written out as a 'word' (in the sense of a free algebra where all powers are collapsed into a product of variables). For example,
-
INPUT x**2, OUTPUT x*x
-
INPUT (x*y**2)**3, OUTPUT x*y*y*x*y*y*x*y*y
If anybody knows a way to do this, it would be much appreciated (I am a beginner to Python). Thanks!
I have had a look at SymPy expand which, for the second example gives the output:
x*y**2*x*y**2*x*y**2
.
But then this is still not fully reduced, and this gives the same problem as of the first example. I think a loop to replace the power operator ** with the corresponding number of multiplications should work, but I am unsure how to implement this.
答案1
得分: 0
一种方法是使用evaluate(False)
上下文管理器来替换幂运算为乘法:
from sympy import *
var("x, y")
def func(base, exp):
values = [base]*exp
return Mul(*values)
with evaluate(False):
expr = x**2 + (x*y**2)**3
res = expr.replace(Pow, func)
print(res)
#输出: x*x + (x*(y*y))*(x*(y*y))*(x*(y*y))
英文:
One way might be to use the evaluate(False)
context manager in order to replace powers with multiplications:
from sympy import *
var("x, y")
def func(base, exp):
values = [base]*exp
return Mul(*values)
with evaluate(False):
expr = x**2 + (x*y**2)**3
res = expr.replace(Pow, func)
print(res)
#out: x*x + (x*(y*y))*(x*(y*y))*(x*(y*y))
Then you would have to manually remove parentheses.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论