-
Notifications
You must be signed in to change notification settings - Fork 23
Andrey Mirugin #19
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?
Andrey Mirugin #19
Conversation
| is_unar = False | ||
| end = -1 | ||
| result_expression = expression | ||
| for i in range(len(result_expression)): |
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.
В данном случае лучше использовать цикл в таком виде:
for index, value in enumerate(result_expression):
...Читается лучше и нет необходимости обращаться к элементам коллекции по индексам.
| result_expression = expression | ||
| for i in range(len(result_expression)): | ||
| if result_expression[i] == "+" or result_expression[i] == "-": | ||
| if not is_unar: |
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.
is_unary
| return result_expression | ||
|
|
||
|
|
||
| def checking_and_solving_comparison(expression): |
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.
- в данном случае функцию лучше назвать
check_and_solve_comparison - Если названии функции отмечено два действия -- это уже звоночек, что функцию необходимо разбить на несколько маленьких. Функция не должна делать несколько разных действий. В идеале она должна быть максимально простой и желательно чистой
| is_comparison = True | ||
| return [comparison[expression[i]+expression[i+1]](calc(expression[0:i]), | ||
| calc(expression[i+2:len(expression)])), is_comparison] | ||
| return [expression, is_comparison] |
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 или стандартный кортеж.
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.
Лучше строить логику функции так, чтобы в ней было наименьшее количество точек выхода из функции. В идеале только один return в конце функции.
| first_element = "" | ||
| start = 0 | ||
| for i in range(1, pointer+1): | ||
| prev = first_element |
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.
previous
неколько симоволов не сделают погоды :)
сокращение не имеет смысла в этом случае
| End position of element | ||
| """ | ||
| end = 0 | ||
| flag = False |
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.
Если необходимо в коде функции использовать флаг, то нужно дать этому флагу осмысленное имя. Человек, который будет читать этот код, не поймет, что значит этот флаг, пока не поймет всю функцию.
| expression = string.EXPRESSION | ||
| expression = replace_spaces(expression) | ||
| expression = add_implicit_mult(expression) | ||
| [expression, is_comparison] = checking_and_solving_comparison( |
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.
Так делать не принято. Распоковка не требует скобочек в выражении с левой стороны, либо, если очень хочется, можно поставить круглые скобки:
(expression, is_comparison) = checking_and_solving_comparison(...)| res_exp = expression | ||
| space_pos = res_exp.find(" ") | ||
| while space_pos != -1: | ||
| if space_pos-1 >= 0 and res_exp[space_pos-1] in ("+", "-", "*", "^", "%", "=", ">", "<", "!", "/", ","): |
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.
В этой функции есть много перечислений операторов, которые имеют какой-то сокральный смысл, недоступный непосвященному :)
Как минимум есть смысл дать всем этим перечислениям осмысленное название.
| def calc(expression): | ||
| """Calculate expression with no spaces""" | ||
| result_expression = expression | ||
| result_expression = replace_long_unaries(result_expression) |
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.
Что ж такое произошло, что функцию replace_long_unaries нужно вызывать 4 раза?
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.
Каждая замена, скобок на их значение и подобные, могла породить унарные знаки. replace_long_unaries убирает их. Поэтому после каждого действия я вызывал её
| elif is_float(expr_right): | ||
| was_float = True | ||
| elif not is_float(expr_right) and was_float: | ||
| result_expression = result_expression[0:i] + \ |
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.
- Модификация коллекции во время итерирования по этой коллекции с помощью цикла
for-- крайне плохая идея. - Спагетти-код, который крайне сложно понять
| maxprior = priority[expression[i]] | ||
| result = calc_by_position_of_sign(position, expression) | ||
| new_string = expression.replace( | ||
| expression[result[1]:result[2]+1], str("{:.16f}".format(result[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.
Без карандаша и листика невозможно представить в голове, что из этого получится.
PythonAndGoCommunity
left a comment
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 или int, к примеру) в зависимости от результата их работы. Функция которая возвращает %data type%, None или рейзит ошибку - хороший пример.
No description provided.