check parentheses whether balance
This function,parChecker assumes that aStackclass is available and returns a boolean result as to whether the string of parentheses is balanced.
from pythonds.basic.stack import Stack
def parChecker(strings):
s = Stack()
balanced = True
index = 0
while (index < len(strings) and balanced:
if (string[index] == '(': # 碰到( push
s.push('(')
else: #碰到)先查看stack是否为空 空就跳出,不空pop
if s.isEmpty():
balanced = False
else:
s.pop()
index += 1
if s.isEmpty() and balanced:
return True
else :
return False
3.7. Balanced Symbols (A General Case)
from pythonds.basic.stack import Stack
def parChecker(strings):
s = Stack()
index = 0
balanced = True
while (index < len(strings) and balanced):
if (strings[index] ='(' or '[' or '{'): # if symbol in "([{"
s.push(strings[index])
elif s.isEmpty(): #下面有代替,运用match函数
balanced = False
elif (strings[index] ==')' and s.peek()='(') or (strings[index] ==']' and s.peek()='[') or (strings[index] =='}' and s.peek()='{'):
s.pop()
else:
balanced = False
index += 1
if s.isEmpty(0 and balanced:
return True
else:
return False
print(parChecker('{{([][])}()}'))
print(parChecker('[{()]'))
'''
else:
top = s.pop()
if not matches(top,symbol):
balanced = False
def matches(open,close):
opens = "([{"
closers = ")]}"
return opens.index(open) == closers.index(close)
'''