Skip to content

Instantly share code, notes, and snippets.

@jul
Last active September 8, 2020 00:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jul/eece1cc6e0d9541ec39e83f9ca535aa2 to your computer and use it in GitHub Desktop.
Save jul/eece1cc6e0d9541ec39e83f9ca535aa2 to your computer and use it in GitHub Desktop.
calculator 4 opérations yoda style :)
#!/usr/bin/python3.7
from functools import reduce
crush_stack=object()
stack=[]
dispatch={
lambda x: True :
print,
str.isdigit :
lambda x: stack.append(int(x)),
lambda x: x in '+*/-' :
lambda op: stack.insert(
0,
int(reduce(
{ '+' : int.__add__,
'*' : int.__mul__,
'-' : int.__sub__,~
'/':int.__truediv__}[op],
stack
))
) or crush_stack,
}
for c in '10 1 + 0 * 2 32 + 13 * 2 - 2 / '.split():
for pred, action in dispatch.items():
if pred(c) and action(c) is crush_stack:
stack=stack[:1]
print("=%d" % stack[0])
"""
10
1
+
=11
0
*
=0
2
32
+
=34
13
*
=442
2
-
=440
2
/
=220
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment