【发布时间】:2022-12-07 06:11:17
【问题描述】:
我需要在 python 中实现这个贪心算法,但我无法理解如何找到 M[j] 最少的“处理器”。下面提供的算法...
greedy_min_make_span(T, m):
# T is an array of n numbers, m >= 2
A = [Nil, ... , Nil] # Initialize the assignments to nil (array size n)
M = [ 0, 0, ...., 0] # initialize the current load of each processor to 0 (array size m)
for i = 1 to n
find processor j for which M[j] is the least.
A[i] = j
M[j] = M[j] + T[i]
# Assignment achieves a makespan of max(M[1], .. M[m])
return A
def greedy_makespan_min(times, m):
# times is a list of n jobs.
assert len(times) >= 1
assert all(elt >= 0 for elt in times)
assert m >= 2
n = len(times)
# please do not reorder the jobs in times or else tests will fail.
# Return a tuple of two things:
# - Assignment list of n numbers from 0 to m-1
# - The makespan of your assignment
A = n*[0]
M = m*[0]
i = 1
for i in range(i, n):
j = M.index(min(M))
A[i] = j
M[j] = M[j] + times[i]
return (A, M)
修复:当我尝试将 A[i] 分配给 j 时,我现在遇到的错误是“列表分配索引超出范围”。
实用功能:
def compute_makespan(times, m, assign):
times_2 = m*[0]
for i in range(len(times)):
proc = assign[i]
time = times[i]
times_2[proc] = times_2[proc] + time
return max(times_2)
我有的测试用例...
def do_test(times, m, expected):
(a, makespan) = greedy_makespan_min(times,m )
print('\t Assignment returned: ', a)
print('\t Claimed makespan: ', makespan)
assert compute_makespan(times, m, a) == makespan, 'Assignment returned is not consistent with the reported makespan'
assert makespan == expected, f'Expected makespan should be {expected}, your core returned {makespan}'
print('Passed')
print('Test 1:')
times = [2, 2, 2, 2, 2, 2, 2, 2, 3]
m = 3
expected = 7
do_test(times, m, expected)
print('Test 2:')
times = [1]*20 + [5]
m = 5
expected =9
do_test(times, m, expected)
现在我没有通过测试用例。我返回的作业与报告的完工时间不一致。我返回的分配是:[0, 0, 1, 2, 0, 1, 2, 0, 1],我声称的 makespan 是:[6, 7, 4]。当我期望 7 时,我的计算 makespan 返回 8。我在执行此算法时有什么想法是错误的吗?
【问题讨论】: