0

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' counter

Hint2: 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?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Arturo Gonzalez
  • 67
  • 1
  • 1
  • 10

1 Answers1

0

But I think you partly misunderstood the task.

There can be many brackets, but no more ")" than "(" (and at the end the number of both types must be equal) And I would think, that the input not only consists of brackets

So you should build a loop (as you did) and

  1. test, whether the char is a bracket or not
  2. if a bracket, so increase the matching counter (you could even have one Counter, but it is easier to understand with two of them
  3. Check, whether the closing Counter is smaller than the opening (if not, so you could break the Loop, cause it is not mathematical)
  4. After the end of the loop you must check, whether there were an error in the Loop or both Counters are not equal. In both cases the string is not "mathematical", otherwise it is.

I could do it in your code, but I think, you should do THIS alone. Most of These things you have already done, but it seems as you did not completly understand, what you have done and have to do.

am2
  • 380
  • 5
  • 21