Python程式:定義支援使用者限速檢查的資料結構
假設我們想要開發一個數據結構,它可以設定過期時間,並支援一個函式,該函式接收使用者ID和時間戳作為引數。此函式將檢查在給定時間戳下,具有給定使用者ID的使用者請求是否失敗。只有當用戶在給定過期時間內進行過成功的請求時,請求才會失敗。
因此,如果輸入類似於expire = 6,則構造一個物件obj,並呼叫函式obj.limit(0,10)、obj.limit(0,16)、obj.limit(0,17)和obj.limit(1,20),則輸出將分別為False、False、True和False,因為對於使用者0,最初沒有請求,所以為false;在時間16時,它不大於上次請求10後的過期時間6;但在17時為true;而最後一個請求是針對使用者1的,所以初始請求為false。
為了解決這個問題,我們將遵循以下步驟:
定義建構函式。這將接收expire引數。
- lastCall := 建立一個字典,其預設值為-1。
- 定義函式limit()。這將接收uid和timestamp引數。
- last := lastCall[uid]
- 如果last等於-1或(last + expire) <= timestamp,則
- lastCall[uid] := timestamp
- 返回False
- 返回True
示例
讓我們來看下面的實現,以便更好地理解:
from collections import defaultdict class RateLimit: def __init__(self, expire): self.expire = expire self.lastCall = defaultdict(lambda: -1) def limit(self, uid, timestamp): last = self.lastCall[uid] if last == -1 or last + self.expire <= timestamp: self.lastCall[uid] = timestamp return False return True expire = 6 obj = RateLimit(expire) print(obj.limit(0,10)) print(obj.limit(0,16)) print(obj.limit(0,17)) print(obj.limit(1,20))
輸入
RateLimit(6) obj.limit(0,10) obj.limit(0,16) obj.limit(0,17) obj.limit(1,20)
輸出
False False True False
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP