Created
May 15, 2019 19:57
-
-
Save tonymontaro/ec785e0120042ff823e4934c61ae09c9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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("") == "" |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated version (accounts for more than a digit, e.g 30):