我知道有类似的问题,但我无法使用它们修改我的代码。使用递归性的线性分区
想象一下,我们有一些工作要做这种成本的时间n = [8,6,7,2,1,4],和3名工人来做。所以如果我们想要计算分区的最佳方式,我们可以评估所有的选项(这是我想用递归函数做的)。这将是所有选项:
1- 1st worker:[8]; 2nd worker:[6]; 3rd worker:[7,2,1,4] --> Cost=max(8, 6 , 7+2+1+4=14)=14
2- 1:[8]; 2:[6,7]; 3:[2,1,4] --> Cost=max(8,13,7)=13 <------ best
3- 1:[8,6]; 2:[7]; 3:[2,1,4] --> Cost=max(14,7,7)=14
4- 1:[8]; 2:[6,7,2]; 3:[1,4] --> Cost=max(8,15,5)=15
5- 1:[8,6]; 2:[7,2]; 3:[1,4] --> Cost=max(14,9,5)=14
6- 1:[8,6,7]; 2:[2]; 3:[1,4] --> Cost=max(21,2,5)=21
7- 1:[8]; 2:[6,7,2,1]; 3:[4] --> Cost=max(8,16,4)=16
8- 1:[8,6]; 2:[7,2,1]; 3:[4] --> Cost=max(14,10,4)=14
9- 1:[8,6,7]; 2:[2,1]; 3:[4] --> Cost=max(21,3,4)=21
10- 1:[8,6,7,2]; 2:[1]; 3:[4] --> Cost=max(23,1,4)=23
显然,8/6,7/2,1,4是做它,因为它是最大pratitions的最小和最佳的选择。我想在Pyhton中设计一个代码,它可以计算任何数量的任务和任意数量的工人的最佳分区。
我开始我的代码是这样的:
def ib(n,j): #n:list with times,j:number of workers
if j==1:
return sum(n) #if we have just 1 worker
else:
for i in range(j-1,len(n)+1): #to explore all the options of the right
left=ib(n[0:i],j-1)
right=sum(n[i:len(n)])
if right>left:
left=right
ib([8,6,7,2,1,4],3)
我的想法是找到最后一名工人的时间的总和,然后再贴上功能将留下一个工人少,直到我刚才1工人。我有一个错误,因为这个功能已经失效了,我得到了左侧的None。我不知道如何解决这个问题。
谢谢:)
我没有在你的if的'else'一侧看到return语句。 –
当然8,1/7,2/6,4(最大:10)是最佳解决方案吗? – m69