Skip to content

Instantly share code, notes, and snippets.

@sevaseva
Last active October 28, 2018 06:58
Show Gist options
  • Save sevaseva/5b5ed1dae8e0928e8f1f6e223d5a8d7c to your computer and use it in GitHub Desktop.
Save sevaseva/5b5ed1dae8e0928e8f1f6e223d5a8d7c to your computer and use it in GitHub Desktop.
custom eval function in python for a nonempty sting that may contain only '0'..'9', '+', '*'
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment