Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Design Log Storage System: ระบบจัดเก็บล็อกแบบระบุช่วงเวลาใน Python

ออกแบบระบบจัดเก็บล็อกที่มี ID และ Timestamp (รูปแบบ Year:Month:Day:Hour:Minute:Second) รองรับ 2 ฟังก์ชัน:

  • Put(id, timestamp): เพิ่มล็อก
  • Retrieve(start, end, granularity): คืน ID ของล็อกในช่วงเวลา ตามระดับละเอียด (Year, Month, Day, Hour, Minute, Second)

ตัวอย่าง:

  • put(1, "2019:01:01:23:59:59")
  • put(2, "2019:01:01:22:59:59")
  • put(3, "2018:01:01:00:00:00")
  • retrieve("2018:01:01:01:01:01", "2019:01:01:23:00:00", "Year") → [1,2,3]
  • retrieve("2018:01:01:01:01:01", "2019:01:01:23:00:00", "Hour") → [1,2]

แนวทางแก้ปัญหา

  1. เก็บล็อกในลิสต์ self.logs = [] เป็น tuple (id, timestamp)
  2. Map granularity ไปยังตำแหน่ง index ในสตริง:
    • Year: 5, Month: 8, Day: 11, Hour: 14, Minute: 17, Second: 20
  3. ตัดสตริง start/end และ timestamp ตาม index แล้วเปรียบเทียบแบบ string

ตัวอย่างโค้ด

class LogSystem(object):
    def __init__(self):
        self.logs = []
    
    def put(self, id, timestamp):
        self.logs.append((id, timestamp))
    
    def retrieve(self, s, e, gra):
        index = {'Year': 5, 'Month': 8, 'Day': 11, 
                 'Hour': 14, 'Minute': 17, 'Second': 20}[gra]
        start = s[:index]
        end = e[:index]
        return [tid for tid, timestamp in self.logs 
                if start <= timestamp[:index] <= end]

ob = LogSystem()
ob.put(1, "2019:01:01:23:59:59")
ob.put(2, "2019:01:01:22:59:59")
ob.put(3, "2018:01:01:00:00:00")
print(list(ob.retrieve("2018:01:01:01:01:01", 
                       "2019:01:01:23:00:00", "Year")))
print(list(ob.retrieve("2018:01:01:01:01:01", 
                       "2019:01:01:23:00:00", "Hour")))

อินพุต

ob.put(1, "2019:01:01:23:59:59")
ob.put(2, "2019:01:01:22:59:59")
ob.put(3, "2018:01:01:00:00:00")
ob.retrieve("2018:01:01:01:01:01","2019:01:01:23:00:00","Year")
ob.retrieve("2018:01:01:01:01:01","2019:01:01:23:00:00","Hour")

เอาต์พุต

[1, 2, 3]
[1, 2]