How to check parentheses of an algebraic expression?

Asked

Viewed 1,348 times

0

I’m trying to solve a problem of a course I’m doing but I’m not able to imagine a way to solve.

I need to create a program where the user type any expression that uses parentheses.

My application should analyze if the expression passed is with the parentheses open and closed in the correct order, and I have no idea how to do this analysis, could help me?

algebra = list()
aberto = fechado = 0
expressao = str(input('Digite sua expressão algébrica com parênteses: '))
if expressao == '(':
    aberto += 1
elif expressao == ')':
    fechado += 1
if aberto == fechado:
    algebra.append(expressao)
    print(f'A sua expressão {algebra} está correta!')
print(f'Sua expressão está incorreta, verifique seus parênteses {algebra}')
  • 2

    I have already solved this problem in C using Polish reverse notation and a stack. I do not know if it is the best solution, because the idea when I did it was to solve the algebraic expression, but it is relatively simple. If it is just for checking, possibly count the number of open and closed parentheses and compare if it is the same amount.

  • Take a look at this project: https://github.com/hausen/exprtut. The idea is to shunting-Yard Algorithm an infix postfixed notation (reverse polish notation, RPN).

  • @Williamjohnadamtrindade then but what he’s doing in his code is getting an infix expression and creating a pos, what I need is to receive a posfixa and check if the parenthesis opening is correct. I did more or less this, but he is still always giving as valid see the code I will put in the question.

  • 3

    An expression any or really an algebraic expression? Its text and its title say contradictory information. For example, (a + b (/c)) is not algebraic, but respects the formula of parentheses.

1 answer

1


def testaparenteses(expr):
    contador = 0
    for c in expr:
        if c == '(':
            contador += 1
        if c == ')':
            if contador > 0:
                contador -= 1
            else:
                return False

    return contador == 0

expressao = 'pi*(Rexterno**2 - Rinterno**2)'
print(testaparenteses(expressao))

expressao = '(x + (y + 1))*(x - (y + 1))'
print(testaparenteses(expressao))

expressao = ')(' # cagado
print(testaparenteses(expressao))

expressao = '(x + 7)**2 = x**2 + 14*x + 49)' # cagado
print(testaparenteses(expressao))
  • 4

    The stack is unnecessary if you do not mix parentheses. Just a counter. In this case, the stack automaton would store a number in unary, hence incrementing would stack, and decrement would pop. To be valid, the counter would be empty and also could not close something that did not open, the equivalent of its second if

  • @Jeffersonquesado, got it. I edited it accordingly.

  • @Marcelouchimura thank you

  • Thanks to @Jeffersonquesado for the suggestion, otherwise my code would be a mess.

  • 4

    I can’t help but comment on the fact that I keep answering questions with code only. Not a single word to describe anything. The community as a whole would earn much more if it described how it addresses the problem and how it solves it, rather than delivering the code ordered as one delivering a cake.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.