Dev Tool/Pycharm

Remove redundant parentheses

#_달 2017. 10. 7. 14:55

Pycharm 사용 중 에러는 아니지만 다음과 같은 문구가 나오는 경우가 있다.


Remove redundant parentheses

This inspection highlights redundant parentheses in statements.


해당 경우는 불필요한 괄호를 사용했을때 나온다.

(파이참 설정에서 해당 밑줄을 제거하는 옵션이 있다.)


예를들어 C++ 에서 if문 사용시

조건식을 괄호 안에 사용한다. ex) if (n != 10) 

하지만 파이썬에서는 괄호가 필요없다. if n != 10:

(if (n != 10): 로 작성하고 실행시켜도 잘 실행된다.)


-----------------------------------------------------------------

아래는 계산식 에서 괄호를 불필요하게 사용하는 경우이다.

ex) (a * b) --> a * b


출처 : https://stackoverflow.com/questions/18400741/remove-redundant-parentheses-from-an-arithmetic-expression


A pair of parentheses is necessary if and only if they enclose an unparenthesized expression of the form X % X % ... % X where X are either parenthesized expressions or atoms, and % are binary operators, and if at least one of the operators % has lower precedence than an operator attached directly to the parenthesized expression on either side of it; or if it is the whole expression. So e.g. in

q * (a * b * c * d) + c

the surrounding operators are {+, *} and the lowest precedence operator inside the parentheses is *, so the parentheses are unnecessary. On the other hand, in

q * (a * b + c * d) + c

there is a lower precedence operator + inside the parentheses than the surrounding operator *, so they are necessary. However, in

z * q + (a * b + c * d) + c

the parentheses are not necessary because the outer * is not attached to the parenthesized expression.

Why this is true is that if all the operators inside an expression (X % X % ... % X) have higher priority than a surrounding operator, then the inner operators are anyway calculated out first even if the parentheses are removed.

So, you can check any pair of matching parentheses directly for redundancy by this algorithm:

Let L be operator immediately left of the left parenthesis, or nil
Let R be operator immediately right of the right parenthesis, or nil
If L is nil and R is nil:
  Redundant
Else:
  Scan the unparenthesized operators between the parentheses
  Let X be the lowest priority operator
  If X has lower priority than L or R:
    Not redundant
  Else:
    Redundant

You can iterate this, removing redundant pairs until all remaining pairs are non-redundant.

Example:

((a * b) + c * (e + f))

(Processing pairs from left to right):

((a * b) + c * (e + f))   L = nil R = nil --> Redundant
^                     ^   
 (a * b) + c * (e + f)    L = nil R = nil --> Redundant
 ^     ^                  L = nil R = + X = * --> Redundant
  a * b  + c * (e + f)    L = * R = nil X = + --> Not redundant
               ^     ^

Final result:

a * b + c * (e + f)