*More fully fledged applications can be found on the Products page. The Bash page is dedicated to fully commented oneliners, and a MySQL quick reference is available here.
#!/usr/bin/python
"""
Will Bergen - 2020
- Balanced parentheses using a stack
- Uses list.append() as push()
- Example usage: ./paren_check.py "((()))"
"""
import sys
# Ensure input:
if len(sys.argv) != 2:
print "need an arg"
exit(1)
# Check input for correct chars:
print "Input: " + sys.argv[1]
for c in sys.argv[1]:
if not (ord(c) == 40 or ord(c) == 41):
print "Invalid input"
exit(1)
# Declare Stack:
stack = []
# For each open, push, for each close, pop
for c in sys.argv[1]:
if c == '(':
stack.append(c)
else:
# Failing pop() is automatically a fail
try:
stack.pop()
except:
print "Not Balanced"
exit(1)
# Anything other than empty stack (ie. empty list) is fail:
if len(stack) == 0:
print "Balanced"
exit(0)
else:
print("Not Balanced")
exit(1)