lr 10

parent 23c3118d
# sem3-ivt19-task1
Простой калькулятор
## Описание задачи
Реализуйте вычиление однооперандных операций в простом калькуляторе.
Процедуры для вычисления разместите внутри функции ```calculate()```
+: (1, 2, 3, 4, 5, 6, 7, 8, 9) = 45.0
+: (1.000001, 2.000002, 3.00005) = 6.000053
+: (1, 2, 3, 4, 5, 6, 7, 8, 9) = 45.0
-: (1, 2, 3, 4, 5, 6, 7, 8, 9) = -45.0
/: (1, 2, 3, 4) = 0.04167
*: (1.0001, 2.2345) = 2.23472
+: (1, 2, 3, 4, 5, 6, 7, 8, 9) = 45.0
...@@ -8,7 +8,6 @@ def print_results(*args, action=None, result=None): ...@@ -8,7 +8,6 @@ def print_results(*args, action=None, result=None):
""" """
operands = args[:len(args)] operands = args[:len(args)]
print('inp_args in pretty mode', operands, action, result) print('inp_args in pretty mode', operands, action, result)
from string import ascii_lowercase from string import ascii_lowercase
...@@ -25,7 +24,6 @@ def print_results(*args, action=None, result=None): ...@@ -25,7 +24,6 @@ def print_results(*args, action=None, result=None):
lst.append(f"{operands[-1]}") lst.append(f"{operands[-1]}")
return lst return lst
arg_list=(" ".join((argsPrint(operands)))) arg_list=(" ".join((argsPrint(operands))))
action_list=(" ".join(actionPrint(operands, action))) action_list=(" ".join(actionPrint(operands, action)))
st = f"{arg_list} {action_list} = {result} |" st = f"{arg_list} {action_list} = {result} |"
...@@ -33,11 +31,8 @@ def print_results(*args, action=None, result=None): ...@@ -33,11 +31,8 @@ def print_results(*args, action=None, result=None):
print(st) print(st)
print('-' * len(st)) print('-' * len(st))
# Пример вывода большого количества аргументов def write_log(*args, action=None, result=None, file='calc-history.log.txt'):
# inp = 100, 200, 300, action = + f = open(file, mode='a', errors='ignore')
#
# ************************************ f.write(f"{action}: {args} = {result} \n")
# * A, B, C * A + B + C * f.close()
# ************************************ \ No newline at end of file
# * 100, 200, 300 * 13579 *
# ************************************
from calcprint import print_results from calcprint import print_results, write_log
PARAMS = {'precision': 0.00001, 'output_type': float, 'possible_types': (int, float)} PARAMS = {'precision': None,
'output_type': None,
'possible_types': None,
'dest': None}
def load_params(file="params.ini"):
global PARAMS
f = open(file, mode='r', errors='ignore')
lines = f.readlines()
for l in lines:
param = l.split('=')
param[1] = param[1].strip('\n')
if param[0] != 'dest':
param[1] = eval(param[1])
PARAMS[param[0]] = param[1]
def convert_precision(prec): def convert_precision(prec):
'''' ''''
...@@ -15,52 +29,52 @@ def convert_precision(prec): ...@@ -15,52 +29,52 @@ def convert_precision(prec):
x=prec.split('.') x=prec.split('.')
return int(len(x[1])) return int(len(x[1]))
def calculate(*args, **kwargs): def calculate(*args, action=None, **kwargs):
load_params()
global result
precision = convert_precision(kwargs['precision']) precision = convert_precision(kwargs['precision'])
output_type = kwargs['output_type'] output_type = kwargs['output_type']
if args[-1] == '+': if action == '+':
result_sum = sum(args[0:-1]) result = sum(args)
if type(result_sum) is not output_type: if type(result) is not output_type:
result_sum = output_type(result_sum) result = output_type(result)
return result_sum
if args[-1] == '-':
result_diff=0
for n in args[0:-1]:
result_diff -= n
if type(result_diff) is not output_type:
result_sum = output_type(result_diff)
return result_diff
if args[-1] == '*': if action == '-':
result_mult = 1 result=0
for n in args[0:-1]: for n in args:
result_mult *= n result -= n
if type(result_mult) is not output_type: if type(result) is not output_type:
result_mult = output_type(result_mult) result = output_type(result)
return round(result_mult, precision)
if args[-1] == '/': if action == '*':
result_division = args[0] result = 1
for n in args[1:-1]: for n in args:
result_division /= n result *= n
if type(result_division) is not output_type: if type(result) is not output_type:
result_division = output_type(result_division) result = output_type(result)
return round(result_division, precision) result = round(result, precision)
if action == '/':
result = args[0]
for n in args:
result /= n
if type(result) is not output_type:
result = output_type(result)
result = round(result, precision)
def test_packed_calc_sum(): write_log(*args, action=action, result = result)
inp1, action = [1, 2, 3, 4, 5, 6, 7, 8, 9], "+" return result
assert calculate(*inp1, action,
**PARAMS) == 45.0, 'Sum of list of ints from 1 to 9'
assert type(calculate(*inp1, action, **
PARAMS)) is type(45.0), 'Type of sum is incorrect'
if __name__ == "__main__": if __name__ == "__main__":
assert calculate(*list(range(1, 10)), "+", **PARAMS) == 45.0 # 1 + 2 + 3 + .. + 9
assert calculate(*list(range(1, 10)), "-", **PARAMS) == -45 load_params()
assert calculate(*list(range(1, 5)), "/", **PARAMS) == 0.04167 print(calculate(*list(range(1, 10)), action = "+", **PARAMS))
assert calculate(*[1.0001, 2.2345], "*", **PARAMS)== 2.23472 assert PARAMS.get('dest') == 'output.txt', "Имя файла для записи истории вызовов функции calculate должно быть output.txt"
print_results(*list(range(1, 10)), action = "+", result=calculate(*list(range(1, 10)), "+", **PARAMS)) write_log(*(1.000001, 2.000002, 3.00005), action='+', result='6.000053')
\ No newline at end of file assert calculate(*list(range(1, 10)), action = "+", **PARAMS) == 45.0 # 1 + 2 + 3 + .. + 9
assert calculate(*list(range(1, 10)), action = "-", **PARAMS) == -45
assert calculate(*list(range(1, 5)), action = "/", **PARAMS) == 0.04167
assert calculate(*[1.0001, 2.2345], action = "*", **PARAMS)== 2.23472
print_results(*list(range(1, 10)), action = "+", result=calculate(*list(range(1, 10)), action = "+", **PARAMS))
\ No newline at end of file
precision=0.00001
output_type=float
possible_types=(int, float)
dest=output.txt
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment