100 XP

83. Decode a repeated string

Advanced stacks parsing

A short way to write repeated text is a count followed by the text in square brackets: 3[ab] stands for ababab. Repeats can sit inside each other: 2[a3[b]] is 2[abbb], which is abbbabbb.

Write a function decode(text) that takes text written this way and returns it written out in full:

  • A count is a whole number of one or more digits, always followed by [: 10[x] is ten x's.
  • Letters outside any brackets stay as they are, wherever they are: x2[y]z is xyyz.
  • Brackets always come in matching pairs, and empty brackets stand for nothing: 3[] is "".

Example 1

Inputtext = "3[ab]"
Output"ababab"
Explanationab, three times.

Example 2

Inputtext = "2[a3[b]]c"
Output"abbbabbbc"
ExplanationThe inner 3[b] first: 2[abbb], then c.

Example 3

Inputtext = "x10[y]"
Output"xyyyyyyyyyy"
ExplanationA two-digit count: ten y's after the x.

Constraints

  • text has 0 to 100 characters: lower-case letters, digits and square brackets, always written as described.
  • Counts are from 1 to 99, and the text written out is at most 1000 characters.

Submit also runs 9 more tests you can't see.

Code
def decode(text):
    """Write out a string with counted repeats.

    text: str, where k[...] means ... repeated k times
    Returns: str, the text written out in full
    """
    # Write your code here
    pass