我还在学习python,而且我仍然很难处理对象,我试图编写一个程序来计算项目中一组活动的关键路径,我已经能够获得活动的关键路径,并且它们被存储为嵌套对象列表,每个对象都有不同的属性,如id,前驱和持续时间,问题我&# 39;我要打印出正确的结果,我想打印出持续时间最长的路径和提供该值的路径本身
class criticalPath:
def __init__(self):
'''
Initialize all the variables we're going to use to calculate the critical path
'''
self.id = None
self.pred = tuple()
self.dur = None
self.est = None
self.lst = None
#list to store all the objects
self.all_objects = list()
def set_properties(self, name, predecessor, duration):
self.id = name
self.pred = tuple(predecessor)
self.dur = duration
def main():
#starting_nodes = list()
object_list = list()
A = criticalPath()
A.set_properties('A', '0', 3)
B = criticalPath()
B.set_properties('B', '0', 6)
C = criticalPath()
C.set_properties('C', 'A', 1)
D = criticalPath()
D.set_properties('D', 'B', 4)
tmp_list = list()
tmp_list.append(A)
tmp_list.append(C)
object_list.append(tmp_list)
tmp_list = list()
tmp_list.append(B)
tmp_list.append(D)
object_list.append(tmp_list)
print('The total duration of the project is {}'.format(max([sum([node.dur for node in object]) for object in object_list])))
#print(max(object_list.id, key=sum(object_list.dur)))
if __name__ == '__main__': main()
我已经打印出总持续时间,在这种情况下为10,我注释掉的最后一行是我最后一次尝试比较object_lists中的对象id,这是基于他们的个人持续时间,即属性& #39; ID'和' dur'每个对象,所以基本上我想得到像这样的输出
项目的关键路径是B ==> D,项目总持续时间为10
答案 0 :(得分:0)
class criticalPath:
def __init__(self):
'''
Initialize all the variables we're going to use to calculate the critical path
'''
self.id = None
self.pred = tuple()
self.dur = None
self.est = None
self.lst = None
#list to store all the objects
self.all_objects = list()
def set_properties(self, name, predecessor, duration):
self.id = name
self.pred = tuple(predecessor)
self.dur = duration
def main():
#starting_nodes = list()
object_list = list()
A = criticalPath()
A.set_properties('A', '0', 3)
B = criticalPath()
B.set_properties('B', '0', 6)
C = criticalPath()
C.set_properties('C', 'A', 1)
D = criticalPath()
D.set_properties('D', 'B', 4)
tmp_list = list()
tmp_list.append(A)
tmp_list.append(C)
object_list.append(tmp_list)
tmp_list = list()
tmp_list.append(B)
tmp_list.append(D)
object_list.append(tmp_list)
print(object_list)
print('The total duration of the project is {}'.format(max([sum([node.dur for node in object]) for object in object_list])))
print([path.id for path in max(object_list, key=lambda ls: sum(obj.dur for obj in ls))])
if __name__ == '__main__': main()