Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added final_task/calc/__init__.py
Empty file.
13 changes: 13 additions & 0 deletions final_task/calc/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import argparse
from calc.main_functions import reduction_expression, check_compared


def main():
try:
parser = argparse.ArgumentParser(description='Takes mathematical expression')
parser.add_argument('string')
s = parser.parse_args().string
composition = reduction_expression(s)
print(check_compared(composition))
except Exception as e:
print('ERROR: ', e)
116 changes: 116 additions & 0 deletions final_task/calc/main_functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
from calc import other_functions
from calc.math_functions import decide_func


class ExpressionError(Exception):
pass

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лишняя пустая строка


def reduction_expression(string):
lis = other_functions.finding_elements(string)
lis = other_functions.additions(lis)
return lis


def check_compared(composition):
i = 0
while i < len(composition)-1:
if composition[i] == '==':
a, b = cut(i, composition)
return a == b
elif composition[i] == '<=':
a, b = cut(i, composition)
return a <= b
elif composition[i] == '>=':
a, b = cut(i, composition)
return a >= b
elif composition[i] == '!=':
a, b = cut(i, composition)
return a != b
elif composition[i] == '>':
a, b = cut(i, composition)
return a > b
elif composition[i] == '<':
a, b = cut(i, composition)
return a < b

i += 1

return decide_expression(composition)


def cut(i, lis):
a = decide_expression(lis[:i])
b = decide_expression(lis[i+1:])
return a, b


def decide_expression(s):
s.insert(0, '(')
s.append(')')
st_nums = []
st_ops = []
i = 0

while i < len(s):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Цикл for

verify(s, i, st_nums, st_ops)
i += 1

if len(st_nums) > 1 or len(st_ops):
print('ERROR: not necessary operation')

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я думаю, в данном случае будет уместо использовать исключения.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можете дать подсказку как это должно выглядеть, потому что я не совсем понял суть использования исключений.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В данном случае вместо print и выхода из программы можно "бросить" исключение, например:

class InvalidExpressionError(Exception):
    pass

if len(st_nums) > 1 or len(st_ops):
    raise InvalidExpressionError

А на самом верхнем уровне, где вызывается функция main, можно эти исключения обрабатывать и корректно завершать программу:

try:
    main()
except Excpetion as e:
    print(f"ERROR: {e})

В таком случае у нас будет только одна точка, где мы завершаем исполнение этой программы, вместо большого количества функций exit.

PS: код приведен для примера, написан "на коленке" и без проверки того, что он работает.

raise ExpressionError

return st_nums[0]


def verify(string, index, st_nums, st_ops):
if type(string[index]) == float:
st_nums.append(string[index])

elif string[index] == '(':
st_ops.append('(')
if other_functions.get_prior(string[index+1]) == 1:
st_nums.append(0)

elif string[index] == ')':
if st_ops[-1] == '(':
del st_ops[-1]
else:
try:
st_nums[-2] = other_functions.perform_bin_operate(st_nums[-2], st_nums[-1], st_ops[-1])
except Exception:
print('ERROR: not necessary element')
raise ExpressionError
del st_ops[-1]
del st_nums[-1]
verify(string, index, st_nums, st_ops)

elif other_functions.get_prior(string[index]) == 5:
args = other_functions.decide_function(index, string)
ready_args = decide_args(args)
string[index] = decide_func(string[index], ready_args)
verify(string, index, st_nums, st_ops)

elif other_functions.get_prior(string[index]) <= other_functions.get_prior(st_ops[-1]):
if string[index] == '^' and st_ops[-1] == '^':
st_ops.append(string[index])
else:
try:
st_nums[-2] = other_functions.perform_bin_operate(st_nums[-2], st_nums[-1], st_ops[-1])
except Exception:
print('ERROR: not necessary element')
raise ExpressionError
del st_nums[-1]
del st_ops[-1]
verify(string, index, st_nums, st_ops)

elif other_functions.get_prior(string[index]) > other_functions.get_prior(st_ops[-1]):
st_ops.append(string[index])


def decide_args(args):
ready_args = []
for s in args:
ready_args.append(decide_expression(s))

return ready_args
44 changes: 44 additions & 0 deletions final_task/calc/math_functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import math


functions_mapping = {
'abs': math.fabs,
'acos': math.acos,
'acosh': math.acosh,
'asin': math.asin,
'asinh': math.asinh,
'atan': math.atan,
'atanh': math.atanh,
'ceil': math.ceil,
'cos': math.cos,
'degrees': math.degrees,
'exp': math.exp,
'expm1': math.expm1,
'fabs': math.fabs,
'factorial': math.factorial,
'log10': math.log10,
'log2': math.log2,
'radians': math.radians,
'sin': math.sin,
'round': round,
'log': math.log,
'pow': math.pow,
}


def decide_func(function, ready_args):
for name, func in functions_mapping.items():
if function == name:
try:
if len(ready_args) == 1:
return float(func(ready_args[0]))
elif len(ready_args) == 2:
return float(func(ready_args[0], ready_args[1]))
else:
print('ERROR: problem with arguments in function "' + function + '"!')
exit()
except Exception:
print('ERROR: problem with arguments in function "' + function + '"!')
exit()
print('ERROR: not find function "' + function + '"!')
exit()
Loading