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

จำนวนโปรแกรมเมอร์ที่ทำงานในเวลาที่กำหนดใน Python

สมมติว่าเรามีรายการช่วงเวลาและอินพุตเวลาอีกตัวหนึ่ง ในแต่ละช่วงโครงสร้างคือ [start, end] แทนเวลาที่โปรแกรมเมอร์ทำงาน เราต้องหาจำนวนโปรแกรมเมอร์ที่กำลังทำงานในเวลานั้น

ตัวอย่าง

หากอินพุตคือ interval = [[2, 6], [4, 10], [5, 9], [11, 14]], time = 5 ผลลัพธ์จะเป็น 3 เนื่องจากที่เวลา 5 มีโปรแกรมเมอร์สามคนทำงาน: [2, 6], [4, 10], [5, 9]

ขั้นตอนการแก้ปัญหา

  1. count := 0
  2. สำหรับแต่ละ interval ใน intervals:
    • ถ้า start ของ interval <= time และ end ของ interval >= time ให้ count := count + 1
  3. คืนค่า count

การใช้งาน

class Solution:
    def solve(self, intervals, time):
        count = 0
        for interval in intervals:
            if interval[0] <= time and interval[1] >= time:
                count += 1
        return count

ob = Solution()
interval = [[2, 6], [4, 10], [5, 9], [11, 14]]
time = 5
print(ob.solve(interval, time))

อินพุต

[[2, 6], [4, 10], [5, 9], [11, 14]], 5

เอาต์พุต

3