-
Notifications
You must be signed in to change notification settings - Fork 27
Aliaksei Milto #28
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Aliaksei Milto #28
Conversation
final_task/calculator/logic.py
Outdated
@@ -0,0 +1,259 @@ | |||
import math as m | |||
|
|||
func_dictionary = {'sin': m.sin, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Подход в лоб. Все функции из модуля можно легко получить динамически.
Вот один из примеров, как можно в рантайме получить абсолютно все вызываемые объекты из модуля
math_functions = [getattr(math, attr) for attr in dir(math) if callable(getattr(math, attr))]
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Я знаю, но мой калькулятор при работе с функциями завязан именно на словаре, а здесь список.
Если есть какой-нибудь эффективный способ сделать именно такой словарь, я исправлю это.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
dict([(attr, getattr(math, attr)) for attr in dir(math) if callable(getattr(math, attr))])
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
dict([(attr, getattr(math, attr)) for attr in dir(math) if callable(getattr(math, attr))])
Оу
Спасибо)
final_task/calculator/logic.py
Outdated
return index | ||
|
||
|
||
def wrapper(Func, Args): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Совсем не очевидный подход.
0) Название этой функции никак не передает то, что в ней происходит.
- Намного лучше будет обрабатывать все исключения на самом высоком уровне, а не задавливать эти исключения всюду таким образом
- В данном случае, если произошло исключение, то программа продолжит свое исполнение, хотя скорее всего приложение должно аварийно заверишть работу
final_task/calculator/logic.py
Outdated
'+', '-', '*', '/', '%', '^', | ||
'>', '<', '=', ')', '!', ',' | ||
): | ||
raise ValueError("""ERROR: invalid argument on position {}""".format(index)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
в данном случае нужны одинарные кавычки, не тройные
final_task/calculator/logic.py
Outdated
elif index < len(eval_string) and eval_string[index] == '(': | ||
variable, index = get_bracket(eval_string, index) | ||
elif index < len(eval_string) and eval_string[index].isalpha(): | ||
str = "" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
название переменной пересекается с классом str
из built-in
советую придумать другое имя для этой переменной
final_task/calculator/logic.py
Outdated
while index < len(eval_string) and (eval_string[index].isalpha() or eval_string[index].isdigit()): | ||
str += eval_string[index] | ||
index += 1 | ||
if (str == 'pi'): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
советую использовать такой же подход, как и с функциями. Маппинг названия константы и значения самой константы.
if (znak == '*'): | ||
mult *= num1 | ||
elif (znak == '/'): | ||
mult /= num1 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Почему в функции под названием "умножение" может происходить деление или возведение в степень? :)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Потому что операции одного приоритета на мой взгляд ;)
И возведения в степень там нет, кстати
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Тогда все равно не могу понять, почему функция называется multiply
final_task/calculator/logic.py
Outdated
return mult, index | ||
|
||
|
||
def sum(eval_string, index): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
название пересекается с built-in
final_task/calculator/logic.py
Outdated
|
||
|
||
def sum(eval_string, index): | ||
sum, num1 = 0, 0 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
а тут уже название пересекается с global
final_task/calculator/logic.py
Outdated
|
||
|
||
def solve_equality(eval_string, index): | ||
num1, num2, znak = 0, 0, "" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
транслит
index += 1 | ||
else: | ||
break | ||
return (float(num), index) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Советую для таких случаев импользовать namedtuple
Зачастую это может знаительно упростить понимание кода
raise ValueError('ERROR: no closing bracket') | ||
|
||
|
||
def error(args): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
эта функция не нужна. Ошибки можно и нужно генерировать прямо там, где они происходят
Thanks to Pavel Dubovik (dubovikmaster)
Tests will be supplemented
Tests will be supplemented
while index < len(eval_string) and (eval_string[index].isalpha() or eval_string[index].isdigit()): | ||
math_object += eval_string[index] | ||
index += 1 | ||
if (math_object == 'pi'): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Подход в лоб. Константы можно получать динамически из модуля.
+ комментарии выше |
pep8