12/36
Part 3 of 8 · Open and closeLearn and do
At [, push what you've built so far. At ], pop it and repeat
In the format 3[ab]c, a number before brackets repeats what's inside, and brackets can nest:
def decode(text):
stack, current, count = [], "", 0
for ch in text:
if ch.isdigit():
count = count * 10 + int(ch)
elif ch == "[":
stack.append((current, count))
current, count = "", 0
elif ch == "]":
before, times = stack.pop()
current = before + current * times
else:
current += ch
return current
print(decode("3[ab]c"))
print(decode("2[a3[b]]"))
print(decode("x10[y]z"))
What does decode("2[a3[b]]") give?
Pick one to see what it prints.
Pick an answer above to see the rest