final

parent 08daf9e7
2020-11-26 13:59:15.377841 : +: (1, 2, 3, 4, 5, 6, 7, 8, 9) = 45.0 2020-12-06 22:01:41.637499 : + : (4.0, 4.0) = 8.0
2020-11-26 13:59:15.421833 : +: (1.000001, 2.000002, 3.00005) = 6.000053 2020-12-06 22:01:41.657444 : - : (2, 10.34) = -8.34
2020-11-26 13:59:15.425833 : +: (1, 2, 3, 4, 5, 6, 7, 8, 9) = 45.0 2020-12-06 22:01:41.658442 : - : (8, 2.3, 0, 4.55) = 1.15
2020-11-26 13:59:15.429832 : -: (1, 2, 3, 4, 5, 6, 7, 8, 9) = -45.0 2020-12-06 22:01:41.658442 : / : (25, 5.0, 2.5) = 2.0
2020-11-26 13:59:15.433831 : /: (1, 2, 3, 4) = 0.04167 2020-12-06 22:01:41.660436 : * : (3.2, 5.6, 1) = 17.92
2020-11-26 13:59:15.433831 : *: (1.0001, 2.2345) = 2.23472 2020-12-06 22:01:41.660436 : + : (3.2, 5.4, 1.0, 6) = 15.6
2020-11-26 13:59:15.433831 : +: (1, 2, 3, 4, 5, 6, 7, 8, 9) = 45.0 2020-12-06 22:02:14.841294 : + : (4.0, 4.0) = 8.0
2020-12-06 22:02:14.859614 : - : (14.2, 4, 5.4) = 4.8
2020-12-06 22:02:14.860605 : - : (5.2, 6.7, 8) = -9.5
2020-12-06 22:02:14.865592 : / : (36, 6.0, 3) = 2.0
2020-12-06 22:02:14.868583 : * : (7, 2.3, 4.9) = 78.89
2020-12-06 22:02:14.868583 : + : (1.7, 4.4, 3.0, 8) = 17.1
2020-12-06 22:03:42.085424 : + : (4.0, 4.0) = 8.0
2020-12-06 22:03:42.104374 : - : (14.2, 4, 5.4) = 4.8
2020-12-06 22:03:42.104374 : - : (5.2, 6.7, 8) = -9.5
2020-12-06 22:03:42.105372 : / : (36, 6.0, 3) = 2.0
2020-12-06 22:03:42.107367 : * : (7, 2.3, 4.9) = 78.89
2020-12-06 22:03:42.108399 : + : (1.7, 4.4, 3.0, 8) = 17.1
2020-12-06 22:04:58.979922 : + : (4.0, 4.0) = 8.0
2020-12-06 22:04:58.997868 : - : (2, 10.34) = -8.34
2020-12-06 22:04:58.998839 : - : (8, 2.3, 0, 4.55) = 1.15
2020-12-06 22:04:58.998839 : / : (25, 5.0, 2.5) = 2.0
2020-12-06 22:04:59.000833 : * : (3.2, 5.6, 1) = 17.92
2020-12-06 22:04:59.000833 : + : (3.2, 5.4, 1.0, 6) = 15.6
2020-12-06 22:05:40.580340 : + : (4.0, 4.0) = 8.0
2020-12-06 22:05:40.597848 : - : (14.2, 4, 5.4) = 4.8
2020-12-06 22:05:40.597848 : - : (5.2, 6.7, 8) = -9.5
2020-12-06 22:05:40.598847 : / : (36, 6.0, 3) = 2.0
2020-12-06 22:05:40.605827 : * : (7, 2.3, 4.9) = 78.89
2020-12-06 22:05:40.606926 : + : (1.7, 4.4, 3.0, 8) = 17.1
...@@ -20,7 +20,7 @@ def print_results(*args, action=None, result=None): ...@@ -20,7 +20,7 @@ def print_results(*args, action=None, result=None):
return lst return lst
def actionPrint(operands, action): def actionPrint(operands, action):
lst=[] lst=[]
for i in range(operands[0],operands[-1]): for i in list(operands[0:-1]):
lst.append(f"{i} {action}") lst.append(f"{i} {action}")
lst.append(f"{operands[-1]}") lst.append(f"{operands[-1]}")
return lst return lst
...@@ -34,5 +34,5 @@ def print_results(*args, action=None, result=None): ...@@ -34,5 +34,5 @@ def print_results(*args, action=None, result=None):
def write_log(*args, action=None, result=None, file='calc-history.log.txt'): def write_log(*args, action=None, result=None, file='calc-history.log.txt'):
f = open(file, mode='a', errors='ignore') f = open(file, mode='a', errors='ignore')
f.write(f"{datetime.now()}: {action}: {args} = {result} \n") f.write(f"{datetime.now()} : {action} : {args} = {result} \n")
f.close() f.close()
\ No newline at end of file
from calcprint import print_results, write_log from calcprint import print_results, write_log
import unittest
PARAMS = {'precision': None, PARAMS = {'precision': None,
'output_type': None, 'output_type': None,
'possible_types': None, 'possible_types': None,
'dest': None} 'dest': None}
def load_params(file="params.ini"): def load_params(file="params.ini"):
''' Функция загружает параметры вычислений из внешнего файла,
которым по умолчанию является params.ini '''
global PARAMS global PARAMS
f = open(file, mode='r', errors='ignore') with open(file, 'r', errors='ignore') as f:
lines = f.readlines() lines = f.readlines()
for l in lines: for l in lines:
param = l.split('=') param = l.split('=')
param[1] = param[1].strip('\n') param[1] = param[1].strip('\n')
if param[0] != 'dest': if param[0] != 'dest':
param[1] = eval(param[1]) param[1] = eval(param[1])
PARAMS[param[0]] = param[1] PARAMS[param[0]] = param[1]
def convert_precision(prec): def convert_precision(prec):
'''' ''''
Преобразует точность данную в виде числа с плавающей точкой в целое число, возможное для использования с функцией round. Преобразует точность данную в виде числа с плавающей точкой в целое число, возможное для использования с функцией round.
>>> convert_precision(0.00001)
5
>>> convert_precision(0.0000000001)
10
>>> convert_precision('s')
None
''' '''
prec=str(prec) prec=str(prec)
for i in prec: for i in prec:
...@@ -29,7 +40,47 @@ def convert_precision(prec): ...@@ -29,7 +40,47 @@ def convert_precision(prec):
x=prec.split('.') x=prec.split('.')
return int(len(x[1])) return int(len(x[1]))
def user_input():
args = []
while True:
val = input("Enter value: ")
try:
if val == "":
break
val = float(val)
except ValueError:
print("Введите число в правильном формате (разделитель дробной части '.') ")
else:
args.append(val)
print(args)
if len(args) <= 1:
return
action = input("action: ")
try:
res = calculate(*args, action=action, **PARAMS)
except Exception:
print("Ошибка вычисления. Результат не определен")
else:
print_results(*args, action=action, result=res)
def calculate(*args, action=None, **kwargs): def calculate(*args, action=None, **kwargs):
''' Главная функция приложения калькулятора, в которой и производятся все вычисления,
а также запись в историю вычислений. Результат приводится к заданному типу данных и округляется до заданного количества знаков
>>> calculate(*list(range(1, 10)), action = "+", **PARAMS)
45.0
>>> calculate(*list(range(1, 10)), action = "-", **PARAMS)
-45
>>> calculate(*list(range(1, 5)), action = "/", **PARAMS)
0.04167
>>> calculate(*[1.0001, 2.2345], action = "*", **PARAMS)
2.23472
'''
load_params() load_params()
global result global result
precision = convert_precision(kwargs['precision']) precision = convert_precision(kwargs['precision'])
...@@ -37,44 +88,57 @@ def calculate(*args, action=None, **kwargs): ...@@ -37,44 +88,57 @@ def calculate(*args, action=None, **kwargs):
if action == '+': if action == '+':
result = sum(args) result = sum(args)
if type(result) is not output_type:
result = output_type(result)
if action == '-': if action == '-':
result=0 result = args[0]
for n in args: for n in args[1:(len(list(args)))]:
result -= n result -= n
if type(result) is not output_type:
result = output_type(result)
if action == '*': if action == '*':
result = 1 result = 1
for n in args: for n in args:
result *= n result *= n
if type(result) is not output_type:
result = output_type(result)
result = round(result, precision)
if action == '/': if action == '/':
result = args[0] result = args[0]
for n in args: if 0 in args[1:len(args)]:
result /= n return 'Деление невозможно'
if type(result) is not output_type: else:
result = output_type(result) for n in args[1:(len(list(args)))]:
result = round(result, precision) result /= n
if type(result) is not output_type:
result = output_type(result)
result = round(result, precision)
write_log(*args, action=action, result = result) write_log(*args, action=action, result = result)
return result return result
class TestCalculator(unittest.TestCase):
def test_summ(self):
self.assertEqual((calculate(*(3.2, 5.4, 1.0, 6), action="+", **PARAMS)), 15.6)
def test_diff_pos(self):
self.assertEqual((calculate(*(8, 2.3, 0, 4.55), action="-", **PARAMS)), 1.15)
def test_diff_neg(self):
self.assertEqual((calculate(*(2, 10.34), action = "-", **PARAMS)), -8.34)
def test_mult(self):
self.assertEqual((calculate(*(3.2, 5.6, 1),action="*", **PARAMS)), 17.92)
def test_div(self):
self.assertEqual((calculate(*(25, 5.0, 2.5), action="/", **PARAMS)), 2.0)
def test_error(self):
with self.assertRaises(Exception):
calculate(*(5,0), action="/", **PARAMS)
calculate(*('yes',5), action="+", **PARAMS)
def test_file(self):
assert PARAMS.get('dest') == 'output.txt', "Имя файла для записи истории вызовов функции calculate должно быть output.txt"
if __name__ == "__main__": if __name__ == "__main__":
load_params() load_params()
print(calculate(*list(range(1, 10)), action = "+", **PARAMS)) user_input()
assert PARAMS.get('dest') == 'output.txt', "Имя файла для записи истории вызовов функции calculate должно быть output.txt" unittest.main()
write_log(*(1.000001, 2.000002, 3.00005), action='+', result='6.000053')
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
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