Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Compute "% off" calculations
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