If I have a set my_set
and I want to check if variable x is contained in the set:
if x in my_set:
Is the time complexity here O(1) ?
If I have a set my_set
and I want to check if variable x is contained in the set:
if x in my_set:
Is the time complexity here O(1) ?
It depends on the data, for example if your set contains string objects(Or any other objects that don't produce the same hash), then the time complexity of membership testing would be O(1).
Hash of string objects are randomly generated for security reasons(I think it's because of dictionary look-ups as keys are strings). Although with different mathematical operations we try our best to avoid hash collisions, they are always possible, so in these cases Python has to continue the probe sequence. I just wanted to give you an overview not to break my first sentence that the time complexity is O(1).
On the other hand, if you have some data which produce the same hash, you won't get O(1).
Here I'm going to force my objects to have identical hash:
from random import randint
class SameHash:
def __hash__(self) -> int:
# return randint(1, 5)
return 1
def __eq__(self, other):
return False
def __repr__(self):
return "SameHash()"
s = {SameHash() for _ in range(5)}
print(s)
SameHash.__eq__ = lambda self, other: print("__eq__ gets called")
SameHash() in s
output:
{SameHash(), SameHash(), SameHash(), SameHash(), SameHash()}
__eq__ gets called
__eq__ gets called
__eq__ gets called
__eq__ gets called
__eq__ gets called
Now uncomment return randint(1, 5)
line and run the script several times to experiment.