Created
January 17, 2017 18:02
-
-
Save Mindstormer619/5fc6c558138546fd90fc3c5bfdeec023 to your computer and use it in GitHub Desktop.
r/dailyprogrammer Challenge #298 [Easy] Solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
exp = raw_input() | |
# assuming exp is balanced | |
stack = [] | |
justClosed = False # did we just close a paren in the last operation | |
for ch in exp: | |
if ch != ')': | |
stack.append(ch) | |
justClosed = False | |
else: | |
poppedItems = [] | |
lastItem = stack.pop() | |
while lastItem != '(': | |
poppedItems.append(lastItem) | |
lastItem = stack.pop() | |
if justClosed == True and len(poppedItems) == 1: | |
stack.append(poppedItems[0]) | |
elif len(poppedItems) == 0: | |
pass # put nothing to the stack | |
else: | |
poppedItems.reverse() | |
stack.append('(' + ''.join(poppedItems) + ')') | |
justClosed = True | |
print ''.join(stack) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment