0

I'm currently doing the "Word Break" problem in LeetCode. It is a dynamic programming problem with the difficulty "Medium". For some extrange reason, the exact code (but without the "class Solution" thing) works in my Code Editor with all cases, but there are some cases in LeetCode that just give me the compeltely opposite output (even though it works in my editor).

What can I do?

def wordBreak(self, s: str, wordDict: List[str], memo={}) -> bool:
    key = s
    if key in memo:
        return memo[key]
    
    if s == "":
        return True
    
    for word in wordDict:
        if s[:len(word)] == word:
            memo[key] = self.wordBreak(s.replace(word, "", 1), wordDict)
            if memo[key] == True:
                return True
    

    return False

For example, the case of wordBreak("a", ["b"]) (the easiest case possible), outputs True in LeetCode, but obviously outputs False in my code editor. It doesn't make sense.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • This is a typical problem you get with Python: the default value `{}` will be created only once, and so if the function is called multiple times without an explicit `memo` argument, the previous `memo` will still live on in the second call. – trincot Aug 16 '23 at 20:10
  • Possible duplicate of: https://stackoverflow.com/questions/366422/how-can-i-avoid-issues-caused-by-pythons-early-bound-default-parameters-e-g-m – Woodford Aug 16 '23 at 20:11
  • Why is `memo` a function parameter? Nothing on the LeetCode page suggests this. – Barmar Aug 16 '23 at 20:12

0 Answers0