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?