Python class variable in recursion function

Viewed 207
class Solution(object):
    def decode(self, s):
        sub_s = ""
        while self.i < len(s) and s[self.i] != "]":
            if not s[self.i].isdigit():
                sub_s += s[self.i]
                self.i += 1
            else:
                n = 0
                while self.i < len(s) and s[self.i].isdigit():
                    n = n * 10 + int(s[self.i])
                    self.i += 1
                self.i += 1
                seq = self.decode(s)
                self.i += 1
                sub_s += seq * n
        return sub_s

    def decodeString(self, s):
        self.i = 0
        return self.decode(s)

I'm working on leetcode problem 394 decoding string problem the problem is to convert a string.

  • s = "3[a]2[bc]", return "aaabcbc".
  • s = "3[a2[c]]", return "accaccacc".
  • s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

The above solution is a Python version which was translated from author bluedawnstar cpp solution.

self.i is maintaining the global state throughout the recursion, is there a more Pythonic way to maintaining such variable instead using self?

2 Answers

You can use the following function instead with no need for a class variable:

def decode(s):
    repeat = output = ''
    index = 0
    while index < len(s):
        char = s[index]
        index += 1
        if char.isdigit():
            repeat += char
        elif char == '[':
            substring, offset = decode(s[index:])
            output += substring * int(repeat)
            index += offset
            repeat = ''
        elif char == ']':
            break
        else:
            output += char
    return output, index

def decodeString(s):
    return decode(s)[0]

so that:

print(decodeString("3[a]2[bc]"))
print(decodeString("3[a2[c]]"))
print(decodeString("2[abc]3[cd]ef"))

outputs:

aaabcbc
accaccacc
abcabccdcdcdef

That's a perfectly fine way to do it.

But it isn't really "global"; it's restricted to that class instance. If you have two instances of the class, each will have their own separate copy of self.i.

Related