我想創建一個只使用python內置模塊的計劃函數,這些模塊將返回最大數量的非重疊約會。函數的輸入是列表的列表,內部列表包含2個整數元素,開始和結束時間。開始時間和結束時間不能改變,如果一次會議的開始時間與另一次會議的結束時間相同,則不認爲它們重疊。例如:安排具有固定開始和結束時間的最大數量任務
輸入:
meetings = [[0, 1], [1, 2], [2, 3], [3, 5], [4, 5]]
max_meetings(meetings)
輸出:
4
的代碼,我現在只是野蠻的力量,並在內存和執行時間瘋狂低效。儘管使用類很有趣,但似乎有更好的方法來實現它。
def max_meetings(meetings):
'''
Return the maximum number of non overlapping meeting that I can attend
input:
meetings - A list of lists. the inner list contains 2 values, the start
time[0] and the end time[1].
returns:
total - The total number of non overlapping meetings that I can attend.
'''
num_meetings = len(meetings)
assert (num_meetings <= 100)
appt_obj = [Appt(o) for o in meetings]
total = 0
for appt in appt_obj:
schedule = Schedule()
schedule.add_meeting(appt)
counter = 0
for comp_appt in appt_obj:
counter += 1
schedule.add_meeting(comp_appt)
# If there isnt a chance, break to save some time
if ((num_meetings - counter) < (total - schedule.meetings)):
break
if schedule.meetings > total:
total = schedule.meetings
return total
class Schedule:
'''
A class to hold my entire schedule. Can add
appointments
'''
def __init__(self):
self.times = set()
self.meetings = 0
def add_meeting(self, appt):
points = range(appt.start, appt.end)
if any(x in self.times for x in points):
pass
else:
# This for loop also seems unnecessary
for p in points:
self.times.add(p)
self.meetings += 1
class Appt:
'''
A class for an appointment
'''
def __init__(self, meeting):
assert (meeting[0] >= 0)
assert (meeting[1] <= 1000000)
self.start = meeting[0]
self.end = meeting[1]
對於第2點,結束時間列表「lst」是按結束時間排序的開始時間列表。 然後對於第3點,在循環內查看所有排序的會議,並將該開始與「lst」列表進行比較?我想我遇到的問題是第一次的定義... – veda905
感謝您的編輯,代碼使得它更清晰您的意思。您的解決方案完美運行,並且比我的解決方案快幾個數量級。您的:** 5.09μs**與我的相比:** 474 ms ** – veda905