I am working with the code that would read the input of the strings and compute whether the parenthesis (using arbitrary characters for open and close) are balanced. The aim is to prompt user to input the amount of brackets as strings, so the compiler would compute their amount and type(ex. if it is '('
or ')'
) .
I have been given hints:
Hint1: introduce two counters initialized to zero in the beginning. Then explore the symbols of the string in a loop. For the current symbol increment the
left
counter by 1 if the symbol is'('
, otherwise, increment by 1 the `right' counterHint2: call a string math-like if the brackets occur like in a mathematical formula. For instance, the strings
'()'
,'(())()'
,'(()())'
are balanced, while the strings'))(())(('
and'())(()'
are not.
My code now looks like this:
lefts =str(input("Please enter a left parenthesis: "))
rights =str(input("Please enter a right parenthesis: "))
#token parsing requires paying attention to the order of the parenthesis
def ptest(test): #testing with counters
lefts = 0
rights = 0
balance = 0 #additional counter that will help us determine the amount of strings and their relation to each other
for c in test:
if c == '(':
balance += 1
lefts += 1
elif c == ')':
balance -= 1
rights += 1
print ('testing "'+test+'"')
print ('lefts='+str(lefts)+' rights='+str(rights))
#if there will b a balance between the strings/parenthesis, they will possibly be balanced
if balance == 0: print 'same number of open/close, possibly balanced'
else: print 'different number of open/close, definitely not balanced'
ptest(test1)
ptest(test2)
How could I modify this in order that it would work?