Created
September 8, 2020 12:33
-
-
Save jul/272233ab96f9cf828d5c05ef52ee1ceb to your computer and use it in GitHub Desktop.
calc v2
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
#!/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