سؤال

I am trying to use Python PLY for a simple expression parser, and I can't get it to work. The code is available at bitbucket, but the offending parts are:

First, the definitions:

def p_expr_minus(p):
    '''expr :   expr MINUS term'''
    p[0] = p[1]-p[3]

and

def p_term_divide(p):
    '''term :   term DIVIDE factor'''
    p[0] = p[1]/p[3]

seem to be inverted, and get me the results: 3-9 = 6 and 2 / 8 = 4.

Second, the parenthesis expression factor: ( expr ) doesn't work. In particular, the part:

def p_factor_brackets(p):
    '''factor : OBRACKET expr CBRACKET'''
    p[0] = p[2]

doesn't function correctly. Parsing an expression such as (9+7) raises:

TypeError: unknown text at ')'

What is the source for these errors?

هل كانت مفيدة؟

المحلول

Your parser is fine, but you are doing something stupid in your main() method:

def main():
    data = "3*4+5*6-10"
    data = raw_input()
    print yacc.parse(data[::-1])

You are feeding the parser with the reversed string: data[::-1]! No wonder that (9+7) gives an error, it is seen as )7+9( by the parser. Just pass the real data and you'll be fine.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top