1

I generally use 'a' in vars() or 'a' in globals() to determine whether the variable a is defined. It works very well most of the time, however, it seems it failed obviously within a recursion stack. Did I get anything wrong here? Could you please give me any help?

here is the code and context: I am working on leetcode question 394. Decode String with recursion.

class Solution:
    def decodeString(self, s: str) -> str:
        # obvous recursion 
        print(s)
        for i in range(len(s)):
            if s[i] == "[":
                start = i    
        for j in range(start+1,len(s)):
            if s[j] == "]":
                end = j
                break
          
#        if "start" not in vars():
#            return s

        substr = s[start+1:end]
        num =""
        for k in range(start-1,-1,-1):
            if s[k].isdigit():
                num = s[k] + num
                start -= 1
            else:
                break 
        
        self.decodeString(s[:start] + substr*int(num) + s[end+1:])

With if start not in locals():return s commented out, at least it can print out the correct result, soon as I uncomment it, it stops at the first iteration, which simply means that start is not in not defined within vars(). Does not vars() work in recursion?

Albert G Lieu
  • 891
  • 8
  • 16
  • 2
    I don't know why you would use `name in vars/global()` in code, even for debugging. You are probably hitting the python surprise of variable scopes, but having variables sometimes-defined is just a bad idea – Cireo May 03 '21 at 20:27
  • 1
    I think you want `'start' in vars()`, not `start in vars`. – John Gordon May 03 '21 at 20:28
  • if ````start```` is not defined, then it means that there is no more "[", then the recursion should stop right there and return the result. – Albert G Lieu May 03 '21 at 20:29
  • See also https://stackoverflow.com/questions/370357/unboundlocalerror-on-local-variable-when-reassigned-after-first-use – Cireo May 03 '21 at 20:31
  • 1
    There is pretty much never a good reason to check if a variable is defined like that. This is a huge red flag about your underlying design here – juanpa.arrivillaga May 03 '21 at 21:04
  • Please, also, provide a [mcve]. Actually provide the code that uses this. Also, please don't add pointless classes like `Solution`. – juanpa.arrivillaga May 03 '21 at 21:06

1 Answers1

2

You should declare start variable before the loop

...
start = None
for i in range(len(s)):
    if s[i] == "[":
        start = i
if start is None:
    return s
...

or you can use else in for loop https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

Victor Ermakov
  • 471
  • 3
  • 6