def __init__(self, maxNumbers):
self.available = set(range(maxNumbers))
def get(self):
return self.available.pop() if self.available else 1
def check(self, number):
return number in self.available
def release(self, number):
self.available.add(number)
4line Python solution using only 1 set and no queue



@agave Well you assume the worst and do
return 1 if not self.available else self.available.pop()
instead of the optimistic (and nicer and shorter)
return self.available.pop() if self.available else 1


@eric_haibin_lin said in 4line Python solution using only 1 set and no queue:
Do you see it anywhere on that page?


My version with more lines but O(1) time for
__init__
class PhoneDirectory(object): def __init__(self, maxNumbers): self.next,self.max,self.released=0,maxNumbers,set() def get(self): if self.next<self.max: self.next+=1 return self.next1 return self.released.pop() if self.released else 1 def check(self, number): return (number in self.released) or self.next<=number<self.max def release(self, number): if number<self.next: self.released.add(number)


The solution looks really neat, maybe I misunderstood the question, but it seems like you are assume set will always give you sorted order when you pop from it, this is undefined behavior, it depends on the implementation of the hash function, in python the hash of an integer is the integer itself, but they can certainly implement in a different way.

@zhongyuan9817 said in 4line Python solution using only 1 set and no queue:
it seems like you are assume set will always give you sorted order when you pop from it
What makes you think that?

@StefanPochmann The test case tells me the order matters, I replaced set with a list, the test breaks.

@zhongyuan9817 The order doesn't matter. I just replaced it with a list as well, and it got accepted. You probably forgot to avoid storing duplicates.

