From 15d8317298f4884f8a2964ad105ed8910583edff Mon Sep 17 00:00:00 2001 From: lsy2246 Date: Sat, 8 Jun 2024 12:07:25 +0800 Subject: [PATCH] =?UTF-8?q?=E7=94=A8=E6=A0=88=E5=AE=9E=E7=8E=B0=E7=9A=84?= =?UTF-8?q?=E8=AE=A1=E7=AE=97=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- python/code/calculator.py | 83 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 python/code/calculator.py diff --git a/python/code/calculator.py b/python/code/calculator.py new file mode 100644 index 0000000..7c5a0e1 --- /dev/null +++ b/python/code/calculator.py @@ -0,0 +1,83 @@ +def format_data(data): + new_data_list = [''] + for i in data: + if new_data_list[-1].isdigit() and i.isdigit(): + new_data_list[-1] += i + else: + new_data_list.append(i) + new_data_list.pop(0) + _static_tmp = [] + formula = [] + + for single_item in new_data_list: + if single_item.isdigit(): + formula.append(single_item) + elif single_item == '(': + _static_tmp.append(single_item) + elif single_item == ')': + while True: + tmp_symbol = _static_tmp.pop(-1) + if tmp_symbol != '(': + formula.append(tmp_symbol) + else: + break + elif single_item in ['*', '/', '%']: + if not _static_tmp: + _static_tmp.append(single_item) + else: + tmp_symbol = _static_tmp.pop(-1) + if tmp_symbol == '(': + _static_tmp.append(tmp_symbol) + _static_tmp.append(single_item) + elif tmp_symbol in ['*', '/', '%']: + formula.append(tmp_symbol) + _static_tmp.append(single_item) + elif tmp_symbol in ['+', '-']: + _static_tmp.append(tmp_symbol) + _static_tmp.append(single_item) + elif single_item in ['+', '-']: + if not _static_tmp: + _static_tmp.append(single_item) + else: + tmp_symbol = _static_tmp.pop(-1) + if tmp_symbol in ['+', '-', '*', '/', '%']: + formula.append(tmp_symbol) + _static_tmp.append(single_item) + elif tmp_symbol == '(': + _static_tmp.append(tmp_symbol) + _static_tmp.append(single_item) + elif single_item == '=': + break + while _static_tmp: + formula.append(_static_tmp.pop(-1)) + + return formula + + +def compute(formula): + if len(formula) == 1: + return formula[0] + else: + for index, item in enumerate(formula): + if item in ['+', '-', '*', '/', '%']: + match item: + case '+': + formula[index - 2] = float(formula[index - 2]) + float(formula[index - 1]) + case '-': + formula[index - 2] = float(formula[index - 2]) - float(formula[index - 1]) + case '*': + formula[index - 2] = float(formula[index - 2]) * float(formula[index - 1]) + case '/': + formula[index - 2] = float(formula[index - 2]) / float(formula[index - 1]) + case '%': + formula[index - 2] = float(formula[index - 2]) % float(formula[index - 1]) + formula.pop(index - 1) + formula.pop(index - 1) + formula = compute(formula) + return formula + + +Equation = "3%2" +formula = format_data(Equation) +result = compute(formula) +print(result) \ No newline at end of file