Monday, February 8, 2016

Python code snipetts


from Stack import Stack
def check_balanced(test_string):
stack = Stack()
for item in test_string:
if item == '(':
stack.push(item)
elif item == ')':
if stack.isempty() or stack.peek() != '(':
print "1 stack was empty when trying to pop or wrong paren"
return False
else:
stack.pop()
elif item == '{':
stack.push(item)
elif item == '}':
if stack.isempty() or stack.peek() != '{':
print "2 stack was empty when trying to pop or wrong item"
return False
else:
stack.pop()
if not stack.isempty():
print "stack was not empty at end"
return False
else:
print "Everything ok"
return True
if __name__ == "__main__":
print check_balanced ("({})")

No comments:

Post a Comment