Python equation parser

后端 未结 3 687
情深已故
情深已故 2021-01-21 16:38

I\'m writing a program which needs a user input for an polynomial function of x. I\'m using Tkinter and python 2.5.

I have a parser method which so far takes the inputt

相关标签:
3条回答
  • 2021-01-21 16:46

    you can use regular expressions,

    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 ))
    

    output:

    coef:-1, exp:2
    coef:3, exp:1
    coef:2, exp:3
    coef:-1, exp:1
    
    0 讨论(0)
  • 2021-01-21 16:48

    Look for "recursive descent parser". It's the canonical method for analysis of strings where some operator precedence is involved.

    0 讨论(0)
  • 2021-01-21 17:02

    It looks like you're implementing something that already exists, in python and other math languages. See for example:

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

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

    0 讨论(0)
提交回复
热议问题