Why does this simple Python code fail the test for "()" ?

  • 0

    The code:

    class Solution(object):
        def isValid(self, str):
            stack = []
            map = {'{':'}','(':')','[':']'}
            for s in str:
                if s in map.keys():
                elif not stack or map[stack.pop()] is not s:
                    return False
            return not stack

    I wrote tests to check the code on my machine. The tests pass, but they fail the same tests when submitted.

  • 3

    You shouldn't rely on equal-value strings being the same object. Use != instead of is not.

  • 0

    Ah, thanks! That worked. Do you know why this worked on my machine?

  • 0

    Python does some string interning and I think that's what makes it for for you. I don't know when exactly it does, I think it mainly has to do with where the strings come from. You can find out more by googling Python string interning.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.