ORD_OF_ZERO = ord('0') def _eval(str): ''' Returns an integer, a result of evaluation of a nonempty str that may contain only '0'..'9', '+', '*'. Summary of the algorithm: * .split('+') the string into products (strings), * then .split('*') each product string into numbers (strings), * evaluate each number (string) into an integer, * multiply all numbers within each product to get the numerical product, * then just add up all numerical products to get The Sum, the result.''' thesum = 0 # The final sum to return in the end. products = str.split('+') for product in products: # Product is a string like '0' or '123' or '5*67*0' theproduct = 1 numbers = product.split('*') for number in numbers: # Number is a string such as '59' or '123' thenumber = 0 for digit in number: # Digit is a character such as '5' or '9' digit_int = ord(digit)-ORD_OF_ZERO # Simply converting a '5' into a 5 thenumber = thenumber*10 + digit_int theproduct *= thenumber thesum += theproduct return thesum