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)
asked Feb 2, 2020 at 4:25
\$\endgroup\$

1 Answer 1

1
\$\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)
answered Feb 2, 2020 at 8:52
\$\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\$ Commented Feb 2, 2020 at 11:30

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.