Python equation parser

后端 未结 3 732
情深已故
情深已故 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
    

提交回复
热议问题