import sys ''' expressions.py Jeff Ondich, 19 May 2010 This program implements and computes values for infix arithmetic expressions involving integers and the plus-sign. It does so by using functions that mimic the productions of this grammar: -> | + -> 0|1|2|3|4|5|6|7|8|9 where is the start symbol and is a single-digit non-negative integer. Each function returns the value of the expression or number that it finds at the beginning of the string passed to it, combined with the string left over after that number or expression has been consumed. For example, expression('2+3') returns (5, ''), while number('4+5') returns (4, '+5'). ''' def expression(s): (value, leftover) = number(s) if len(leftover) > 0: if leftover[0] == '+': (tmpValue, leftover) = expression(leftover[1:]) value += tmpValue else: raise Exception('Invalid expression') return (value, leftover) def number(s): if len(s) == 0 or not s[0].isdigit(): raise Exception('Invalid numerical constant') return (ord(s[0]) - ord('0'), s[1:]) if __name__ == '__main__': if len(sys.argv) != 2: sys.stderr.write('Usage: %s arithmetic-expression\n' % (sys.argv[0])) exit() arithmeticExpression = sys.argv[1] try: (value, leftover) = expression(arithmeticExpression) except Exception, e: print e exit() if len(leftover) > 0: print '"%s" is an invalid expression' % (arithmeticExpression) else: print 'The value of %s is %d' % (arithmeticExpression, value)