+ 1

Is there a way to improve this program? I feel like it’s more complicated than it needs to be.

https://code.sololearn.com/c15G9F3IC5RD/?ref=app """ As input, this program takes a string of characters containing parentheses. First, it outputs a list of tupls, each of which contains the indices of an open parenthesis and it's matching closed parenthesis. After printing the list, the program prints every block enclosed by parentheses in the original input. example: input ((2(3, 4, 5, (6, ))7, 8, (9, )10, 11)) output [(13, 17), (3, 18), (25, 29), (1, 36), (0, 37)] =============================================== (6, ) (3, 4, 5, (6, )) (9, ) (2(3, 4, 5, (6, ))7, 8, (9, )10, 11) ((2(3, 4, 5, (6, ))7, 8, (9, )10, 11)) """ a = input() #self explanatory point = 0 #pointer stac = [] #self explanatory b = [] #to hold tupls that hold the index of each parenthesis and it's partner while point < len(a): if a[point] is '(': stac.append(point) point += 1 # if point is at '(' pack the stac and increment point elif a[point] is ')': c = (stac[-1], point) b.append(c) stac = stac[:-1] point += 1 #if point is at '(' pop, append (Top_of_stac, point) to b and increment point else: point += 1 #otherwise, increment point print(b) #self explanatory print('\n') print('=' * 47) print('\n') #self explanatory for i in b: print(a[i[0]: i[1] + 1]) # For each tupl in b print(a[tupl[0]: tupl[1]+ 1])

24th Sep 2019, 1:25 AM
Evan
1 Odpowiedź
+ 1
Your approach is the right one, but you can make it a little bit shorter. a = input() b = [] stac = [] for point in range(len(a)): if a[point] is "(": stac.append(point) elif a[point] is ")": b.append((stac.pop(-1), point)) print(b) print("\n"+"-"*42+"\n") for i, j in b: print(a[i:j+1])
24th Sep 2019, 1:38 AM
Diego
Diego - avatar