1
\$\begingroup\$

I would like to know if this is a good approach to finding out all the expressions within brackets. (I was actually asked to find out the smallest bracket expression, I have omitted the function to check for the smallest string and spaces within the expression).

s = "((a+b*d)*(x/2))*(1+(y+(x-2)/10))"
b = []
j = 0
b.append(j)
stack = []

for i in range(0, len(s)):
    if s[i] == '(':
        j = j + 1
        b.append(j)        
        b[j] = ''
    elif s[i] == ')':
        b[j] = b[j] + ')'        
        stack.append(b[j])
        j = j - 1

    # 0 is omitted to exclude characters outside of brackets  
    for k in range(1, j + 1):
        b[k] = b[k] + s[i]

print(s)
print(stack)
\$\endgroup\$
0
\$\begingroup\$

Your code works, but is difficult to understand. Especially it is hard to understand what exactly is stored in b, this list contains both integers and strings. The name b also does not give a clue what it used for.

I would suggest a more straight forward method with more descriptive names for variables:

s = "((a+b*d)*(x/2))*(1+(y+(x-2)/10))"

opening_bracket_pos = []
stack = []

for i in range(0, len(s)):
    if s[i] == '(':
        opening_bracket_pos.append(i)
    elif s[i] == ')':
        start_pos = opening_bracket_pos.pop()
        stack.append(s[start_pos: i+1])

print(s)
print(stack)
\$\endgroup\$
1
  • \$\begingroup\$ Thank you for your review, Jan. Also, thanks for the pop line. It reduced the need for an additional loop which I made with k. Question : How can I measure which one is faster ? time python3 brackets.py gives 0 seconds. \$\endgroup\$ – anjanesh Feb 2 '20 at 11:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.