Created
November 27, 2020 23:43
-
-
Save mtimkovich/ce1327e3271839e39cbc252e77a8891a to your computer and use it in GitHub Desktop.
Compute "% off" calculations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import ply.lex as lex | |
import ply.yacc as yacc | |
tokens = ['NUMBER', 'MINUS', 'PERCENT'] | |
t_ignore = ' \t' | |
t_MINUS = r'-' | |
t_PERCENT = r'%' | |
def t_NUMBER(t): | |
r'\d+(\.\d*)?' | |
t.value = float(t.value) | |
return t | |
def t_error(t): | |
print(f'Illegal character {t.value[0]!r}') | |
t.lexer.skip(1) | |
lex.lex() | |
def p_expr(p): | |
'expr : NUMBER MINUS NUMBER PERCENT' | |
p[0] = p[1] - (p[1] * p[3] / 100) | |
def p_error(p): | |
print(f'Syntax error at {p.value!r}') | |
yacc.yacc() | |
if len(sys.argv) < 2: | |
print('expr required') | |
sys.exit(1) | |
expr = ' '.join(sys.argv[1:]) | |
result = yacc.parse(expr) | |
print(f'{result:.2f}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment