贪心算法(Greedy Algorithm)是指在求解目标问题的若干步骤中,每一步总是作出在当前看来是最好的选择,以期望获得问题的全局最优解。
贪心算法的目标是要获得问题的最优解,为此在每一步总是选择当前情况下的最优策略。
(是否能够得到最优解,需要通过证明来确定)
看如下例题:题目说明
使用贪心算法的前提是要按一定规则排序,当前有序序列的第一个元素一定进入最优解,由于活动具有三个属性(活动名称,开始时间,结束时间),在这里我们根据题意选择对活动的结束时间(fi)排序(快速排序),对其中的某一个属性来排序我们可以用类来实现,当然也可以把它拆分为两个列表,活动名称和开始时间为一个列表,结束时间单独为一个列表,这样就可以对结束时间这个列表进行从小到大的排序了,在下面我会用两种方法实现。
类实现:
class task():
def __init__(self,name,start,end):
self.name = name
self.start= start
self.end = end
def __str__(self):
return "['%s',%d,%d]" % (self.name,self.start,self.end)
def __repr__(self):
return self.__str__()
def QuickSort(mylist,start,end):
if start < end:
i,j = start,end
base = mylist[i]
while i < j:
while (i < j) and (mylist[j].end >= base.end):
j -= 1
mylist[i] = mylist[j]
while (i < j) and (mylist[i].end <= base.end):
i += 1
mylist[j] = mylist[i]
mylist[i] = base
QuickSort(mylist,start,i-1)
QuickSort(mylist,j+1,end)
return mylist
def get_max(joblist):
job_schedule = []
num_jobs = len(joblist)
for n in range(num_jobs):
if not job_schedule:
job_schedule.append(joblist[n])
else:
if job_schedule[-1].end <= joblist[n].start:
job_schedule.append(joblist[n])
return job_schedule
if __name__=="__main__":
joblist = [task('1',3,5),task('2',1,4),task('3',0,6),task('4',3,8),task('5',5,7),task('6',6,10),task('7',5,9),task('8',8,11),task('9',2,13),task('10',8,12)]
list_final = QuickSort(joblist,0,len(joblist)-1)
print(get_max(list_final))
拆分列表实现:
joblist = [['1',3,5],['2',1,4],['3',0,6],['4',3,8],['5',5,7],['6',6,10],['7',5,9],['8',8,11],['9',2,13],['10',8,12]]
def finish(joblist):
finlist = []
for i in range(len(joblist)):
finlist.append(joblist[i][-1])
return finlist
def QuickSort(finlist,start,end):
if start < end:
i,j = start,end
base = finlist[i]
all = joblist[i]
while i < j:
while (i < j) and (finlist[j] >= base):
j -= 1
finlist[i] = finlist[j]
joblist[i] = joblist[j]
while (i < j) and (finlist[i] <= base):
i += 1
finlist[j] = finlist[i]
joblist[j] = joblist[i]
finlist[i] = base
joblist[i] = all
QuickSort(finlist,start,i-1)
QuickSort(finlist,j+1,end)
return joblist
def task(joblist):
job_sch = []
num_jobs = len(joblist)
QuickSort(finish(joblist),0,len(joblist)-1)
for n in range(num_jobs):
if not job_sch:
job_sch.append(joblist[n])
else:
if job_sch[-1][2] <= joblist[n][1]:
job_sch.append(joblist[n])
return job_sch
if __name__=="__main__":
print(task(joblist))
(只有一点干货,文采不好,各种词穷,不喜勿喷~)