Codewars: Valid Parentheses

Description

Write a python function such that it takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid.

Examples:

Constraints

0 <= input.length <= 100

Along with opening ( and closing ) parenthesis, input may contain any valid ASCII characters. Furthermore, the input string may be empty and/or not contain any parentheses at all. Do not treat other forms of brackets as parentheses (e.g. [], {}, <>).

Code:

def valid_parentheses(string):

valid=[]

for s in string:

if s==”(“:

valid.append(s)

elif s==”)”:

try:

valid.pop()

except:

return False

if len(valid)==0:

return True

else:

return False

Explanation:

1.iterate each character in string

2.if s==”(“ character is added to list “valid”

3.if s==”)” charcter is poped which was added before

4.if character “)” is not found “False” is returned

5.if lenght of “valid” is 0 then True is returned

6.else False is returned

more at onlyLang

A Blogger,more content at onlylang.blogspot.com