-
-
Save technillogue/5882175 to your computer and use it in GitHub Desktop.
A simple python calculator using lambda expressions
This file contains hidden or 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
operations = { | |
"+": lambda x, y: x + y, | |
"-": lambda x, y: x - y, | |
"/": lambda x, y: x / y, | |
"*": lambda x, y: x * y | |
} | |
def calculate(expr): | |
numxChars = "" | |
operation = None | |
numyChars = "" | |
for char in expr: | |
if char.isdigit(): | |
if operation is None: | |
numxChars += char | |
else: | |
numyChars += char | |
elif char in operations: | |
operation = char | |
elif char.isspace: | |
pass | |
else: | |
raise Exception("invalid charecter: " + char) | |
return operations[operation](int(numxChars), int(numyChars)) | |
print calculate(raw_input("Input? ")) | |
This file contains hidden or 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
$ python calc.py | |
Input? 1 + 1 | |
2 | |
Input? 2/1 | |
2 | |
Input? 3-4 | |
-1 | |
Input? 7*5 | |
35 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can i using this case for big number have 1000 charactor?