forked from realpython/materials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkalkulator.py
More file actions
27 lines (21 loc) · 729 Bytes
/
Copy pathkalkulator.py
File metadata and controls
27 lines (21 loc) · 729 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import operator
import parse
OPERATIONS = {
"pluss": operator.add, # Addition
"minus": operator.sub, # Subtraction
"ganger": operator.mul, # Multiplication
"delt på": operator.truediv, # Division
}
EXPRESSION = parse.compile("{operand1:g} {operation} {operand2:g}")
def calculate(text):
if (ops := EXPRESSION.parse(text)) and ops["operation"] in OPERATIONS:
operation = OPERATIONS[ops["operation"]]
return operator.call(operation, ops["operand1"], ops["operand2"])
if __name__ == "__main__":
for calculation in [
"20 pluss 22",
"2022 minus 1991",
"45 ganger 45",
"11 delt på 3",
]:
print(f"{calculation} = {calculate(calculation)}")