I'm trying to understand one of the most elegant solutions to a Leetcode problem (Remove Invalid Parentheses) provided by the legendary Leetcode ace StefanPochmann: https://leetcode.com/problems/remove-invalid-parentheses/discuss/75028/Short-Python-BFS
What I find confusing is that he initalises a dictionary (the level variable below) with a string (the s input variable):
def removeInvalidParentheses(self, s):
def isvalid(s):
ctr = 0
for c in s:
if c == '(':
ctr += 1
elif c == ')':
ctr -= 1
if ctr < 0:
return False
return ctr == 0
level = {s} # what the heck?
while True:
valid = filter(isvalid, level)
if valid:
return valid
level = {s[:i] + s[i+1:] for s in level for i in range(len(s))}
I've never seen such an idiosyncratic dictionary initialisation. Why would this make sense?
I guess I code post this question on Leetcode but experience-wise it takes quite a bit of time to get a response there - I hope to get a faster response here.