将多项式用SymPy表示为文字。

huangapple go评论60阅读模式
英文:

Write polynomial as word using SymPy

问题

我想输入一个多项式,并将多项式的输出以“单词”的形式写出(即在自由代数的意义上,其中所有的幂都折叠成变量的乘积)。例如,

  1. 输入 x**2,输出 x*x

  2. 输入 (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,

  1. INPUT x**2, OUTPUT x*x

  2. 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.

huangapple
  • 本文由 发表于 2023年6月27日 21:56:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76565618.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定