I want to check whether a key exists in a dictionary. The most appropriate way, as per my knowledge is:
if d_.get(s):
. But, while attempting a question on Leetcode, there was a TLE error when I was using this method. However, when I tried if s in d_
, TLE was gone. I want to know why in
is faster than get()
.
I tried going through some questions, found this one where there is an explanation for d_.get()
v/s d_[s]
. None of the questions addressed d_.get()
v/s s in d_
.
Just in case, some context:
The code that failed with if self.memo.get(s):
:
from typing import List
class Solution:
def __init__(self):
self.word_dict = {}
self.memo = {}
def word_break(self, s):
if not s:
return True
if self.memo.get(s):
return self.memo[s]
res = False
for word in self.word_dict.keys():
if len(word) <= len(s) and s[:len(word)] == word:
res = res or self.word_break(s[len(word):])
self.memo[s] = res
return res
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
for word in wordDict:
self.word_dict[word] = 1
return(self.word_break(s))
The code than got accepted with if s in self.memo
:
from typing import List
class Solution:
def __init__(self):
self.word_dict = {}
self.memo = {}
def word_break(self, s):
if not s:
return True
if s in self.memo:
return self.memo[s]
res = False
for word in self.word_dict.keys():
if len(word) <= len(s) and s[:len(word)] == word:
res = res or self.word_break(s[len(word):])
self.memo[s] = res
return res
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
for word in wordDict:
self.word_dict[word] = 1
return(self.word_break(s))
I always presumed that in
would be slower than fetching attributes(here, get()
).