Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python program to check matching of simple parentheses

I came across this exercise of checking whether or not the simple brackets "(", ")" in a given string are matched evenly.

I have seen examples here using the stack command which I haven't encountered yet. So I attempted a different approach. Can anyone tell me where I am going wrong?

def matched(str):
    ope = []
    clo = []
    for i in range(0,len(str)):
        l = str[i]
        if l == "(":
            ope = ope + ["("]
        else:
            if l == ")":
                clo = clo  + [")"]
            else:
                return(ope, clo)
    if len(ope)==len(clo):
        return True
    else:
        return False

The idea is to pile up "(" and ")" into two separate lists and then compare the length of the lists. I also had another version where I had appended the lists ope and clo with the relevant I which held either ( or ) respectively.

like image 442
Vishesh Avatar asked Aug 08 '16 16:08

Vishesh


People also ask

How do you check whether the parentheses are correctly matched or not?

Push an opening parenthesis on top of the stack. In case of a closing bracket, check if the stack is empty. If not, pop in a closing parenthesis if the top of the stack contains the corresponding opening parenthesis. If the parentheses are valid,​ then the stack will be empty once the input string finishes.

How do you check for valid parentheses in Python?

To solve a valid parentheses problem optimally, you can make use of Stack data structure. Here you traverse through the expression and push the characters one by one inside the stack. Later, if the character encountered is the closing bracket, pop it from the stack and match it with the starting bracket.

How do you use parentheses in Python?

Standard Parentheses - ( ) Broadly speaking, the primary use of parentheses in Python is to call an object. That is the reason why standard parentheses are sometimes called the "call operator." Aside from their main use, parentheses are also used to define generator expressions.


1 Answers

A very slightly more elegant way to do this is below. It cleans up the for loop and replaces the lists with a simple counter variable. It also returns false if the counter drops below zero so that matched(")(") will return False.

def matched(str):
    count = 0
    for i in str:
        if i == "(":
            count += 1
        elif i == ")":
            count -= 1
        if count < 0:
            return False
    return count == 0
like image 57
Henry Prickett-Morgan Avatar answered Oct 21 '22 15:10

Henry Prickett-Morgan