how to parse standard algebraic notation

Chris Angelico rosuav at gmail.com
Wed Oct 1 10:38:35 CEST 2014


On Wed, Oct 1, 2014 at 5:01 PM, math math <mathematisch at gmail.com> wrote:
> What would be a good starting strategy for writing a program to take the derivative of a polynomial expression, such as this below?:
> "x**3 + x**2 + x + 1"
>
> I am a bit confused about my overall strategy. Should one be writing a parser class to split the input on operators and then on the double asterisks? Are there more clever ways? Or is this something one should solve using mathematical formulas instead of parsing the characters?
>
> I just wonder how a seasoned Pythonian would go about a problem like this without using a ready-made derivative function from some module.

Well, let's see. Are you planning to use exact Python syntax
everywhere? For instance, will you use asterisks for multiplication
("5*x**3 + 2*x**2 - 5*x + 1")? If so, you could make use of the
ast.parse() module to do some of the work for you. Otherwise, you'll
have to start by writing up a grammar: exactly what is and isn't
allowed? Then write a parser, and see how things go from there.

ChrisA



More information about the Python-list mailing list