






















part 1. 给 时间 和 IP, 看在提供的input里面如果ip 超出了一个threshold,判断为机器人,output 机器人的ip
input: following string, and threshold
1, ip1
1, ip2
1, ip1
4, ip1
4, ip2
5, ip3
isBot(String input, 3) -> ip1
isBot(String input, 2) -> ip1, ip2
isBot(String input, 1) -> ip1, ip2, ip3
part 2. 给 时间 和 IP, 但是有需要看 sliding time window 里面的 ip 数量 超出了一个 threshold,output true/false
# class CheckBot {
# public CheckBot(int threshold, int windowSize) {
# }
# public boolean isBot(int timestamp, String ip) {
# }
# }
# example:
# Checkbot cb = new CheckBot(threshold = 3, sliding time size = 3);
# isBot(0, ip1) -> false
# isBot(1, ip1) -> false
# isBot(1, ip1) -> true // reached threshold 3 within the time window of 3
# isBot(4, ip2) -> false
# isBot(5, ip1) -> false
1 from collections import Counter 2 3 def isBot(input_str, threshold): 4 # Parse the input string into a list of IPs 5 # We ignore the timestamp for this specific part as per the example 6 lines = input_str.strip().split('\n') 7 ips = [line.split(', ')[1] for line in lines if line] 8 9 # Count occurrences 10 counts = Counter(ips) 11 12 # Filter by threshold 13 bots = [ip for ip, count in counts.items() if count >= threshold] 14 15 # Sort or format as needed (returning list for clarity) 16 return sorted(bots) 17 18 # Testing 19 data = """ 20 1, ip1 21 1, ip2 22 1, ip1 23 4, ip1 24 4, ip2 25 5, ip3 26 """ 27 28 print(f"Threshold 3: {isBot(data, 3)}") # ['ip1'] 29 print(f"Threshold 2: {isBot(data, 2)}") # ['ip1', 'ip2'] 30 print(f"Threshold 1: {isBot(data, 1)}") # ['ip1', 'ip2', 'ip3']
1 from collections import deque, defaultdict 2 3 class CheckBot: 4 def __init__(self, threshold, window_size): 5 self.threshold = threshold 6 self.window_size = window_size 7 # defaultdict automatically creates a deque for any new IP key 8 self.history = defaultdict(deque) 9 10 def is_bot(self, timestamp, ip): 11 # 1. Add current timestamp (auto-creates deque if ip is new) 12 self.history[ip].append(timestamp) 13 14 # 2. Remove timestamps that have fallen out of the sliding window 15 # Logic: Window includes [timestamp - window_size + 1, timestamp] 16 # Example: timestamp 4, window 3 -> valid range is [2, 3, 4]. 17 # Anything <= (4 - 3) i.e. 1 is expired. 18 while self.history[ip] and self.history[ip][0] <= timestamp - self.window_size: 19 self.history[ip].popleft() 20 21 # 3. Check if count meets or exceeds threshold 22 return len(self.history[ip]) >= self.threshold 23 24 # --- Example Usage --- 25 cb = CheckBot(threshold=3, window_size=3) 26 27 print(f"Time 0, ip1: {cb.is_bot(0, 'ip1')}") # False 28 print(f"Time 1, ip1: {cb.is_bot(1, 'ip1')}") # False 29 print(f"Time 1, ip1: {cb.is_bot(1, 'ip1')}") # True (3 hits at/after time -2) 30 print(f"Time 4, ip2: {cb.is_bot(4, 'ip2')}") # False 31 print(f"Time 5, ip1: {cb.is_bot(5, 'ip1')}") # False (Timestamps 0 and 1 expired)
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。