Diff of /tools/calculator.py [000000] .. [6cf5c7]

Switch to unified view

a b/tools/calculator.py
1
'''
2
input: formula strings
3
output: the answer of the mathematical formula
4
'''
5
import os
6
import re
7
from operator import pow, truediv, mul, add, sub
8
import wolframalpha
9
query = '1+2*3'
10
11
def calculator(query: str):
12
    operators = {
13
        '+': add,
14
        '-': sub,
15
        '*': mul,
16
        '/': truediv,
17
    }
18
    query = re.sub(r'\s+', '', query)
19
    if query.isdigit():
20
        return float(query)
21
    for c in operators.keys():
22
        left, operator, right = query.partition(c)
23
        if operator in operators:
24
            return round(operators[operator](calculator(left), calculator(right)),2)
25
26
def WolframAlphaCalculator(input_query: str):
27
    try:
28
        wolfram_alpha_appid = "<YOUR_WOLFRAMALPHA_APP_ID>"
29
        wolfram_client = wolframalpha.Client(wolfram_alpha_appid)
30
        res = wolfram_client.query(input_query)
31
        assumption = next(res.pods).text
32
        answer = next(res.results).text
33
    except:
34
        raise Exception("Invalid input query for Calculator. Please check the input query or use other functions to do the computation.")
35
    # return f"Assumption: {assumption} \nAnswer: {answer}"
36
    return answer
37
38
if __name__ == "__main__":
39
    query = 'max(37.97,76.1)'
40
    print(WolframAlphaCalculator(query))