You are given an expression with numbers, brackets and operators. For this task only the brackets matter. Brackets come in three flavors: "{}" "()" or "[]". Brackets are used to determine scope or to restrict some expression. If a bracket is open, then it must be closed with a closing bracket of the same type. The scope of a bracket must not intersected by another bracket. For this task, you should to make a decision to correct an expression or not based on the brackets. Do not worry about operators and operands.
Input: An expression with different of types brackets. A string (unicode).
Output: The correctness the expression or don’t. A boolean.
Example:
1
2
3
4
5
6
|
checkio( "((5+3)*2+1)" ) = = True
checkio( "{[(3+1)+2]+}" ) = = True
checkio( "(3+{1-1)}" ) = = False
checkio( "[1+1]+(2*2)-{3/3}" ) = = True
checkio( "(({[(((1)-2)+3)-3]/3}-3)" ) = = False
checkio( "2+3" ) = = True
|
How it is used: When you write code or complex expressions in a mathematical package, you can get huge headache when it comes to excess or missing brackets. This concept can be useful for your own IDE.
Precondition: There are only brackets ("{}" "()" or "[]"), digits or operators ("+" "-" "*" "/").
0 < |expression| < 103
判断括号是否匹配,不好好思考还挺容易写错的,换了3个思路才过。
record = {}
def check(expression, target1, target2):
tag1 = tag2 = None
reverse_expression = expression[::-1]
tag1 = expression.find(target1)
tag2 = reverse_expression.find(target2)
if tag1 == -1 and tag2 == -1:
return True
if tag2 == -1 or tag1 == -1:
return False
tag2 = len(expression)-tag2-1
return checkio(expression[tag1+1:tag2])
def checkio(expression):
if expression in record:
return record[expression]
record[expression] = check(expression, '(', ')') and check(expression, '[', ']') and check(expression, '{', '}')
return record[expression]
print checkio('(((([[[{{{3}}}]]]]))))')
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio(u"((5+3)*2+1)") == True, "Simple"
assert checkio(u"{[(3+1)+2]+}") == True, "Different types"
assert checkio(u"(3+{1-1)}") == False, ") is alone inside {}"
assert checkio(u"[1+1]+(2*2)-{3/3}") == True, "Different operators"
assert checkio(u"(({[(((1)-2)+3)-3]/3}-3)") == False, "One is redundant"
assert checkio(u"2+3") == True, "No brackets, no problem"
一个非常美的代码,虽然效率不高
def checkio(Expression):
'Check expression for correct brackets order'
x = "".join(a for a in Expression if a in "{}()[]")
while ("()" in x) or ("[]" in x) or ("{}" in x):
x=x.replace("()","")
x=x.replace("{}","")
x=x.replace("[]","")
return len(x)==0