我正在尝试编写python代码以使用最低成本方法解决运输问题。我有一个 2D numpy 数组,我正在迭代它以找到最小值,使用该最小值执行计算,然后将其替换为 0,以便在values
匹配时循环停止constantarray
,一个相同形状的数组只包含 0s。values
数组包含从supply
中的点到demand
中的点的距离。我目前正在使用 while 循环来执行此操作,但循环没有运行,因为 values.all() != constantarray.all() 的计算结果为 False。
我还需要在编辑数组后重复该过程以移动到values
中的下一个最低数字。
constarray = np.zeros((len(supply),len(demand)) #create array of 0s
sandmoved = np.zeros((len(supply),len(demand)) #used to store information needed for later
totalcost = 0
while values.all() != constantarray.all(): #iterate until `values` only contains 0s
m = np.argmin(values,axis = 0)[0] #find coordinates of minimum value
n = np.argmin(values,axis = 1)[0]
if supply[m] > abs(demand[m]): #all demand numbers are negative
supply[m]+=demand[n] #subtract demand from supply
totalcost +=abs(demand[n])*values[m,n]
sandmoved[m,n] = demand[n] #add amount of 'sand' moved to an empty array
values[m,0:-1] = 0 #replace entire m row with 0s since demand has been filled
demand[n]=0 #replace demand value with 0
elif supply[m]< abs(demand[n]):
demand[n]+=supply[m] #combine positive supply with negative demand
sandmoved[m,n]=supply[m]
totalcost +=supply[m]*values[m,n]
values[:-1,n]=0 #replace entire column with 0s since supply has been depleted
supply[m] = 0
还有一个额外的 if 语句用于何时supply[m]==demand[n]
但我觉得没有必要。我已经尝试使用嵌套的 for 循环,以及许多不同的语法组合一段时间循环,但我就是无法让它按照我想要的方式工作。即使自行运行代码块,m 和 n 也保持不变,并且该函数从values
中删除一个值,但不会将其添加到sandmoved
中。任何想法都非常感谢!!
好吧,这是我的一个旧实现的例子:
import numpy as np
values = np.array([[3, 1, 7, 4],
[2, 6, 5, 9],
[8, 3, 3, 2]])
demand = np.array([250, 350, 400, 200])
supply = np.array([300, 400, 500])
totCost = 0
MAX_VAL = 2 * np.max(values) # choose MAX_VAL higher than all values
while np.any(values.ravel() < MAX_VAL):
# find row and col indices of min
m, n = np.unravel_index(np.argmin(values), values.shape)
if supply[m] < demand[n]:
totCost += supply[m] * values[m,n]
demand[n] -= supply[m]
values[m,:] = MAX_VAL # set all row to MAX_VAL
else:
totCost += demand[n] * values[m,n]
supply[m] -= demand[n]
values[:,n] = MAX_VAL # set all col to MAX_VAL
溶液:
print(totCost)
# 2850
基本上,首先选择一个高于所有给定值的MAX_VAL
和一个totCost = 0
.然后按照算法的标准步骤操作。查找最小单元格的行索引和列索引,例如m
、n
。选择第 m 个电源或第 n 个需求,以较小者为准,然后将您选择的内容乘以values[m,n]
添加到totCost
,并将所选行或列的所有条目设置为MAX_VAL
以避免在下一次迭代中出现这种情况。通过减去所选值来更新较大的值,然后重复直到所有值都等于MAX_VAL
。