# Smallest expression within brackets

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)


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)

• 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. – anjanesh Feb 2 '20 at 11:30