Beispiel #1
0
    def containsNearbyAlmostDuplicate(self, nums: List[int], k: int,
                                      t: int) -> bool:
        n = len(nums)
        if n == 0 or k <= 0 or t < 0: return False

        d = OrderedDict()

        for i, e in enumerate(nums):
            pool = [num[0] for num in d.keys()]
            pool.sort()
            print(f"Keys are: {' '.join(map(str, pool))}")
            l_b = bisect.bisect_left(pool, e)

            print(f"Foud lower bound {l_b} for e={e} at i={i}")
            if l_b < len(pool) and pool[l_b] <= e + t: return True
            u_b = bisect.bisect_right(pool, e - t - 1)

            print(f"Foud upper bound {u_b} for e={e - t - 1} at i={i}")
            if u_b < len(pool) and pool[u_b] >= e - t and pool[u_b] <= e:
                return True

            if len(d) == k:
                d.popitem(last=False)

            d[(e, i)] = i

        return False
class LRUCache:
    def __init__(self, capacity):
        self.cache = OrderedDict()
        self.capacity = capacity

    def get(self, key):
        if key in self.cache:
            self.cache.move_to_end(key)

        return self.cache.get(key, -1)

    def put(self, key, value):
        if key in self.cache:
            self.cache.move_to_end(key)
        else:
            if len(self.cache) >= self.capacity:
                self.cache.popitem(last=False)

        self.cache[key] = value
Beispiel #3
0
    def rob(self, nums: List[int]) -> int:
        if not nums:
            return 0
        if len(nums) <= 2:
            return max(nums)

        dp = OrderedDict()
        dp[0], dp[1] = nums[0], max(nums[0], nums[1])

        for i in range(2, len(nums)):
            dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])

        return dp.popitem()[1]
Beispiel #4
0
class ISBNCache:
    def __init__(self, size):
        self.cache = OrderedDict()
        self.size = size

    # O(1)
    def lookup(self, isbn):
        if isbn in self.cache:
            self.cache.move_to_end(isbn)
            return self.cache[isbn]
        return -1

    # O(1)
    def insert(self, isbn, price):
        if isbn in self.cache:
            del self.cache[isbn]
        self.cache[isbn] = price

        if len(self.cache) > self.size:
            self.cache.popitem(last=False)  # Remove least recent isbn

    # O(1)
    def remove(self, isbn):
        return self.cache.pop(isbn, None) is not None
 def lengthOfLongestSubstring(self, s: str) -> int:
     substring = OrderedDict()
     max_length = 0
     for char in s:
         if char in substring:
             popped = ''
             while popped != char:
                 popped = substring.popitem(False)
             
         substring[char] = True
         
         substring_length = len(substring)
         if substring_length > max_length:
             max_length = substring_length
     
     return max_length
Beispiel #6
0
class LRUCacheStrategy(MemoryCacheStrategy[K, V]):
    """strategy which enforces a size limit with LRU"""
    __slots__ = ("storage", "lock", "max_entries")

    storage: OrderedDict[K, V]

    lock: Lock  # OrderedDict is not thread safe

    max_entries: int

    def __init__(self, max_entries: int) -> None:
        self.storage = OrderedDict()
        self.lock = Lock()
        self.max_entries = max_entries

    def __eq__(self, other: object) -> bool:
        if isinstance(other, LRUCacheStrategy):
            return self.storage == other.storage \
                and self.max_entries == other.max_entries
        return NotImplemented

    def __getitem__(self, key: K) -> V:
        """get a value, setting it as the most recently used one"""
        with self.lock:
            self.storage.move_to_end(
                key, last=False)  # higher index = longer time since last use
            return self.storage[key]

    def __setitem__(self, key: K, value: V) -> None:
        """set a value, removing old ones if necessary"""
        with self.lock:
            if key not in self.storage and len(
                    self.storage) == self.max_entries:
                self.storage.popitem(
                )  # make space for new entry by removing the last element
            self.storage[key] = value

    def __delitem__(self, key: K) -> None:
        """remove a value"""
        with self.lock:
            del self.storage[key]

    def __iter__(self) -> Iterator[K]:
        return iter(self.storage)

    def __len__(self) -> int:
        return len(self.storage)

    def __contains__(self, key: object) -> bool:
        return key in self.storage

    def keys(self) -> KeysView[K]:
        return self.storage.keys()

    def values(self) -> ValuesView[V]:
        return self.storage.values()

    def items(self) -> ItemsView[K, V]:
        return self.storage.items()

    def peek(self, key: K) -> V:
        """get the value of key without triggering side effects like changing its priority"""
        with self.lock:
            return self.storage[key]

    @overload
    def pop(self, key: K) -> V:
        ...

    @overload
    def pop(self, key: K, default: Union[V, T] = ...) -> Union[V, T]:
        ...

    def pop(self,
            key: K,
            default: Union[V,
                           T] = POP_SENTINEL) -> Union[V, T]:  # type: ignore
        """remove a value and return it"""
        with self.lock:
            if default is POP_SENTINEL:
                return self.storage.pop(key)
            return self.storage.pop(key, default)

    def popitem(self) -> Tuple[K, V]:
        """remove the least recently used key-value pair and return it"""
        with self.lock:
            return self.storage.popitem()

    def clear(self) -> None:
        """remove all values"""
        with self.lock:
            self.storage.clear()