【问题标题】:Python equation parserPython方程解析器
【发布时间】:2013-12-20 11:33:24
【问题描述】:

我正在编写一个程序,它需要用户输入 x 的多项式函数。我正在使用 Tkinter 和 python 2.5。

我有一个解析器方法,到目前为止,它采用输入的方程并将其拆分为项而不丢失符号。

我想获取每个术语并对其进行解析以获得(系数,度)的元组。例如,-2x^3 返回 (-2,3)。然后我可以将它们添加到数组中并在程序中相应地操作它们。

有没有办法或标准模块可以做到这一点?

这里是解析方法的开始。

def parse(a):
    termnum=[]
    terms=[]
    hi=[]
    num1=0
    num=0
    f=list(a)

    count=0
    negative=False
    coef=0.0
    deg=0.0
    codeg=[]
    for item in f:
        if (item=='-' or item=='+') and count!=0:
            termnum.append(count)
        count+=1
    for item in termnum:
        num1=num
        num=item
        current=''
        while num1<num:
            current=current+f[num1]
            num1+=1
        terms.append(current)
    num1=num
    num=len(f)
    current=''
    while num1<num:
        current=current+f[num1]
        num1+=1
    terms.append(current)
    print terms
parse('-x^2+3x+2x^3-x')

谢谢! P.S 我不想使用外部包。

【问题讨论】:

标签: python parsing tk equation


【解决方案1】:

你可以使用正则表达式,

import re

test = '-x^2+3x+2x^3-x'

for m in re.finditer( r'(-{0,1}\d*)x\^{0,1}(-{0,1}\d*)', test ):
    coef, expn = list( map( lambda x: x if x != '' and x != '-' else x + '1' ,
                            m.groups( ) ))
    print ( 'coef:{}, exp:{}'.format( coef, expn ))

输出:

coef:-1, exp:2
coef:3, exp:1
coef:2, exp:3
coef:-1, exp:1

【讨论】:

    【解决方案2】:

    寻找“递归下降解析器”。这是分析涉及某些运算符优先级的字符串的规范方法。

    【讨论】:

      【解决方案3】:

      看起来您正在用 python 和其他数学语言实现一些已经存在的东西。例如:

      http://www.gnu.org/software/octave/doc/interpreter/Solvers.html

      http://stat.ethz.ch/R-manual/R-devel/library/base/html/solve.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-18
        • 1970-01-01
        • 2011-09-18
        • 2013-03-29
        • 2012-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多