Remove redundant parentheses python что это
Перейти к содержимому

Remove redundant parentheses python что это

  • автор:

Remove Redundant Parenthesis in an Arithmetic Expression

Remove Redundant Parenthesis in an Arithmetic Expression

I’m trying to remove redundant parentheses from an arithmetic expression. For example, if I have the expression (5+((2*3))) , I want the redundant parenthesis between (2*3) removed. The output that I want is (5+(2*3)) .

I’m getting this arithmetic expression from performing an inorder traversal on an expression tree. The final string that I get after performing the traversal is ((5)+(((2)*(3)))) . I used re.sub(‘((d+))’, r’1′, <traversal output string>) to remove the parenthesis between the numbers like (5) to 5 . But I’m still confused on how I should approach to remove parenthesis among sub expressions ( ((2*3)) in this case).

Here is what my inorder traversal function looks like

Any guidance on how I should approach to solve this problem would be appreciated!

Solution – 1

Instead of adding the parenthesis around the parent/root expression, one option is to add the parentheses before and after recursing down on each of the left and right children. If those children are leaves, meaning they do not have children, do not add parentheses.

In practice, this might look something like this:

This means that a tree with a single node, 5, will become just "5" , and the following tree

To instead get the output "(5+((2*3)))" , add an additional set of parenthesis around the returned string if the tree is not a leaf.

Русские Блоги

Python3 отмечает исследование характеристики 36-PEP8 код

При использовании PyCharm, ультраправое будет иметь волнистую линию код предупреждения не соответствуетСтандарты PEP8 кодОтказ Запишите то, что было неправильно и совершенные решения

PEP8 стиль неправильно, а не ошибок кодирования. Просто, чтобы сделать код более читаемость.

1)block comment should start with #

Этот совет при использовании # комментария, вам необходимо добавить пробел после #, а затем написать комментарий содержание

2) отсутствует пробел после «» или отсутствующий пробел после „:“

При использовании, или: когда нужно пространство для раскола в спине

Совет, не нужно пространство впереди, удалить пустое пространство

4)class name should use CamelCase convention

Название Совет класс должен использовать слово заглавной путь к имени, введите первую букву каждого слова в названии

5)expected 2 blank lines ,found 1

Это побудило две пустые строки. Найдено только 0 или 1. Может наноситься на две пустые строки

6)remove redundant parentheses

Запрашивает снять скобки, если класс не наследует другие классы. Может не нужно добавлять после имени класса (). () Могут быть удалены

7)Triple double-quoted strings should be used for docstrings

Вы должны использовать три двойные кавычки. Написать в классе и метод с использованием комментариев одиночных кавычек. Заменено двойные кавычки на нем

8)too many blank lines(2)

Подсказка пустая строка между слишком много и метод пустой линии на линии

9)shadows name ‘xxxx’ from outer scope

Naming конфликтов, предполагая, что внешние переменные и локальные переменные в методе именования то же самое. Совет риск. Под именем переменной может быть изменено

10)Too broad exception clause

Совет поймать исключение слишком широким, и не направлены. Вы можете добавлять комментарии в Ьгу заявление

Python – How to ignore the “redundant parentheses” feature in PyCharm

PyCharm decides that certain parenthesis in my Python code are 'redundant'. I want to keep them anyway. So PyCharm started annoying me with green lines under them. I don't want to give in to PyCharm's quirks.

I was able to ignore other warnings in the following way:

File > Settings > Editor > Inspections > uncheck all warnings that you don't like..

Sadly, the 'redundant parentheses' warning does not appear in that list.

How do I ignore this warning?

Best Solution

redundant parenthesis is a weak warning. You can just uncheck the box there.

Remove redundant parentheses python что это

Given a valid expression Exp containing only binary operators ‘+‘, ‘‘, ‘*‘, ‘/‘, and operands, remove all the redundant parenthesis. A set of parenthesis is said to be redundant if, removing them, does not change the value of the expression.

Example:

Input: Exp = (A*(B+C))
Output: A*(B+C)
Explanation: The outermost parenthesis are redundant.

Input: Exp = A+(B+(C))
Output: A+B+C
Explanation: All the parenthesis are redundant.

Approach: This can be solved with the following idea:

The goal is to discover which brackets from an expression can be safely eliminated by combining stack-based parsing with operator precedence rules. A further array can be used to keep track of whether each character in the input string is a redundant bracket in addition to three arrays to track the Previous and Next operators for each location.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *