PYTHON ONLY! PLEASE FOLLOW DIRECTIONS! DIRECTIONS: import sys import stdio from
ID: 3836602 • Letter: P
Question
PYTHON ONLY! PLEASE FOLLOW DIRECTIONS!
DIRECTIONS:
import sys
import stdio
from linkedstack import Stack
# Reads in a string as command-line argument and writes True if its
# parentheses are properly balanced and False otherwise.
def main():
# Read a string s as command-line argument.
...
# Build a stack.
...
# Define a variable balanced and set it to True.
...
# Enumerate the characters c in s. If c is any of the opening parenthesis,
# push it onto the stack. Otherwise, set balanced to False and break
# the loop if either the stack is empty or if the value atop the stack
# doesn't open c.
for c in s:
...
# The parentheses in s are balanced if balanced is True and the stack
# is empty.
...
if __name__ == '__main__':
main()
Explanation / Answer
Please find my implementation:
import sys
import stdio
from linkedstack import Stack
# Reads in a string as command-line argument and writes True if its
# parentheses are properly balanced and False otherwise.
def main():
# Read a string s as command-line argument.
s = sys.argv
# Build a stack.
stack = []
# Define a variable balanced and set it to True.
isBalanced = True
pushChars, popChars = "<({[", ">)}]"
# Enumerate the characters c in s. If c is any of the opening parenthesis,
# push it onto the stack. Otherwise, set balanced to False and break
# the loop if either the stack is empty or if the value atop the stack
# doesn't open c.
for c in s :
if c in pushChars :
stack.append(c)
elif c in popChars :
if not len(stack) :
isBalanced = False
else :
stackTop = stack.pop()
balancingBracket = pushChars[popChars.index(c)]
if stackTop != balancingBracket :
isBalanced = False
else :
isBalanced = False
# The parentheses in s are balanced if balanced is True and the stack
# is empty.
if isBalanced and not len(stack):
print True
else:
print False
if __name__ == '__main__':
main()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.