final

parent 7d3efded
......@@ -33,3 +33,19 @@
2020-12-10 11:49:47.014899 : / : (25, 5.0, 2.5) = 2.0
2020-12-10 11:49:47.016894 : * : (3.2, 5.6, 1) = 17.92
2020-12-10 11:49:47.017892 : + : (3.2, 5.4, 1.0, 6) = 15.6
2020-12-10 14:53:14.404546 : * : (4.0, 3.0, 2.0, 62.0) = 1488.0
2020-12-10 14:53:14.484896 : - : (2, 10.34) = -8.34
2020-12-10 14:53:14.485893 : - : (8, 2.3, 0, 4.55) = 1.15
2020-12-10 14:53:14.486890 : / : (25, 5.0, 2.5) = 2.0
2020-12-10 14:53:14.488885 : * : (3.2, 5.6, 1) = 17.92
2020-12-10 14:53:14.488885 : + : (3.2, 5.4, 1.0, 6) = 15.6
2020-12-24 12:34:30.506825 : - : (8, 2.3, 0, 4.55) = 1.15
2020-12-24 12:34:30.534744 : / : (25, 5.0, 2.5) = 2.0
2020-12-24 12:34:30.537736 : * : (3.2, 5.6, 1) = 17.92
2020-12-24 12:34:30.538733 : + : (3.2, 5.4, 1.0, 6) = 15.6
2020-12-24 12:35:56.150849 : - : (2, 10.34) = -8.34
2020-12-24 12:35:56.151815 : - : (8, 2.3, 0, 4.55) = 1.15
2020-12-24 12:35:56.152843 : / : (25, 5.0, 2.5) = 2.0
2020-12-24 12:35:56.157801 : * : (3.2, 5.6, 1) = 17.92
2020-12-24 12:35:56.158796 : + : (3.2, 5.4, 1.0, 6) = 15.6
2020-12-24 13:08:11.592307 : + : (3.0, 4.0) = 7.0
from datetime import datetime
def print_results(*args, action=None, result=None):
"""
Вывод в табличном виде результатов вычислений
......@@ -18,6 +17,7 @@ def print_results(*args, action=None, result=None):
for i in operands:
lst.append(f"| {i} |")
return lst
def actionPrint(operands, action):
lst=[]
for i in list(operands[0:-1]):
......@@ -33,6 +33,7 @@ def print_results(*args, action=None, result=None):
print('-' * len(st))
def write_log(*args, action=None, result=None, file='calc-history.log.txt'):
from datetime import datetime
f = open(file, mode='a', errors='ignore')
f.write(f"{datetime.now()} : {action} : {args} = {result} \n")
f.close()
\ No newline at end of file
from calcprint import print_results, write_log
import unittest
PARAMS = {'precision': None,
'output_type': None,
'possible_types': None,
'dest': None}
PARAMS = {
'precision': None,
'output_type': None,
'possible_types': None
}
def load_params(file="params.ini"):
''' Функция загружает параметры вычислений из внешнего файла,
......@@ -12,11 +14,12 @@ def load_params(file="params.ini"):
global PARAMS
try:
open(file, 'r', errors='ignore')
except FileNotFoundError:
f = open(file, 'r', errors='ignore')
f.close()
except FileNotFoundError:
print("Такого файла с параметрами не существует")
else:
with open(file, 'r', errors='ignore') as f:
with open(file, 'r', errors='ignore') as f:
lines = f.readlines()
for l in lines:
param = l.split('=')
......@@ -26,6 +29,7 @@ def load_params(file="params.ini"):
param[1] = eval(param[1])
PARAMS[param[0]] = param[1]
def convert_precision(prec):
''''
Преобразует точность данную в виде числа с плавающей точкой в целое число, возможное для использования с функцией round.
......@@ -35,19 +39,20 @@ def convert_precision(prec):
10
>>> convert_precision('s')
None
'''
prec=str(prec)
'''
prec = str(prec)
for i in prec:
if i=='e':
x=prec.split('-')
if i == 'e':
x = prec.split('-')
return int(x[1])
if i==".":
x=prec.split('.')
if i == ".":
x = prec.split('.')
return int(len(x[1]))
def user_input():
args = []
while True:
val = input("Enter value: ")
try:
......@@ -55,7 +60,9 @@ def user_input():
break
val = float(val)
except ValueError:
print("Введите число в правильном формате (разделитель дробной части '.') ")
print(
"Введите число в правильном формате (разделитель дробной части '.') "
)
else:
args.append(val)
......@@ -63,15 +70,17 @@ def user_input():
if len(args) <= 1:
return
print("Введите один из знаков действия: +, -, *, / ")
action = input("action: ")
try:
res = calculate(*args, action=action, **PARAMS)
except Exception:
print("Ошибка вычисления. Результат не определен")
print("Ошибка вычисления. Результат не определен")
else:
print_results(*args, action=action, result=res)
def calculate(*args, action=None, **kwargs):
''' Главная функция приложения калькулятора, в которой и производятся все вычисления,
а также запись в историю вычислений. Результат приводится к заданному типу данных и округляется до заданного количества знаков
......@@ -88,7 +97,7 @@ 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']
if action == '+':
......@@ -111,43 +120,15 @@ def calculate(*args, action=None, **kwargs):
else:
for n in args[1:(len(list(args)))]:
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
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_precision(self):
self.assertEqual(convert_precision(0.0000001), 7)
self.assertEqual(convert_precision(0.001), 3)
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__":
load_params()
user_input()
unittest.main()
precision=0.00001
output_type=float
possible_types=(int, float)
dest=output.txt
\ No newline at end of file
possible_types=(int, float)
\ No newline at end of file
from calculate import calculate, load_params, convert_precision, PARAMS
import unittest
if __name__=="__main__":
load_params()
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_precision(self):
self.assertEqual(convert_precision(0.0000001), 7)
self.assertEqual(convert_precision(0.001), 3)
def test_error(self):
with self.assertRaises(Exception):
calculate(*(5, 0), action="/", **PARAMS)
calculate(*('yes', 5), action="+", **PARAMS)
unittest.main()
\ 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