Skip to content

Instantly share code, notes, and snippets.

@tonymontaro
Created May 15, 2019 19:57
Show Gist options
  • Select an option

  • Save tonymontaro/ec785e0120042ff823e4934c61ae09c9 to your computer and use it in GitHub Desktop.

Select an option

Save tonymontaro/ec785e0120042ff823e4934c61ae09c9 to your computer and use it in GitHub Desktop.
def decode(word, index=0):
word_set = []
while index < len(word):
char = word[index]
if char == ']':
break
elif char.isdigit():
new_word_set, index = decode(word, index + 2)
word_set = word_set + int(char) * new_word_set
else:
word_set.append(char)
index += 1
return word_set, index
def decode_word(word):
return ''.join(decode(word)[0])
assert decode_word("3[a]2[bc]") == "aaabcbc"
assert decode_word("3[a2[c]]") == "accaccacc"
assert decode_word("2[abc]3[cd]ef") == "abcabccdcdcdef"
assert decode_word("abc") == "abc"
assert decode_word("3[a]") == "aaa"
assert decode_word("3[ab]") == "ababab"
assert decode_word("3[a2[c]]") == "accaccacc"
assert decode_word("2[2[2[a]]]") == "aaaaaaaa"
assert decode_word("") == ""
@tonymontaro
Copy link
Author

Updated version (accounts for more than a digit, e.g 30):

def decode(word, index=0):
    word_set = []
    while index < len(word):
        char = word[index]
        if char == ']':
            break
        elif char.isdigit():
            count = 1
            while char.isdigit():
                char = word[index + count]
                count += 1
            multiplier = word[index:index+(count - 1)]
            new_word_set, index = decode(word, index + count)
            word_set = word_set + int(multiplier) * new_word_set
        else:
            word_set.append(char)
        index += 1

    return word_set, index

def decode_word(word):
    return ''.join(decode(word)[0])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment