Last active
September 8, 2020 00:12
-
-
Save jul/eece1cc6e0d9541ec39e83f9ca535aa2 to your computer and use it in GitHub Desktop.
calculator 4 opérations yoda style :)
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 | |
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