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)
1 Answer 1
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)
-
\$\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– anjanesh2020年02月02日 11:30:13 +00:00Commented Feb 2, 2020 at 11:30