Skip to content

Instantly share code, notes, and snippets.

@jul
Created Sep 8, 2020
Embed
What would you like to do?
calc v2
#!/usr/bin/python3.7
from functools import reduce
push_to_stack=object()
stack=[]
OP="+/-*"
all_true=lambda x: True
def crush_stack():
global stack
stack=stack[:1]
print("=%d" % stack[0])
dispatch={
all_true: print,
lambda st : st.isdigit() or st[0] in '+-' and st[1:].isdigit():
lambda x: stack.append(int(x)),
lambda x: x in OP:
lambda op: stack.insert(
0,
int(reduce(
{ '+' : int.__add__,
'*' : int.__mul__,
'-' : int.__sub__,
'/':int.__truediv__}[op],
stack
)
)) or crush_stack,
}
def tokenize(stream):
print(stream)
buff=""
for c in stream:
if c in OP:
if buff: yield buff
buff=c
elif c in "0123456789":
buff+=c
else:
if buff:
yield buff
buff=""
if buff: yield buff
PRED=0
ACTION=1
update_state = lambda stream: list(map(
lambda el: any(map(
lambda guide: guide[PRED](el) and guide[ACTION](el) is crush_stack,
dispatch.items())) and crush_stack(), ## or print(stack), # debug
tokenize(stream)
))
update_state("1 -20 +3 + 2 / 4 1 1 + -1 OOOO A O 1 +")
stack.clear()
update_state('10 1 + 0 * 2 32 + 13 * 2 - 2 / 7 / 1 +')
print(stack)
update_state("1 +")
print(stack)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment