我有一个名为weight
的变量,它是一个充满int值的列表。在循环的每一轮之后,我想要么隐藏当前的最小值,要么用“o”替换它,这样我就可以找到下一个最小值。weight = [4,2,4,1,3,5,6,2,3]
例如会变成[4, 2, 4, 'o', 3, 5, 6, 2, 3]
。。我遇到的问题是,当循环进行第二次运行时,它产生了一个错误,因为添加了'o'。你知道吗
def greedyMinWt():
weight = [4,2,4,1,3,5,6,2,3]
value = [7,9,9,8,5,8,3,5,2]
itemPick = [4,2,4,1,3,5,6,2,3]
val = 0
weightCount = 0
itemCounter = 0
valueCount = 0
totalWeight = 0
totalValue = 0
weightInput = -1
pickedItems = []
n=0
capacity = 17
print('Itm|' + ' Wt|' + ' Val' )
for num in range(0,len(weight)):
print('(' + str(num+1) + ')' + '\t ' + str(weight[num]) + '\t ' + str(value[num]))
print('\nSolve by greedy min wt:')
while totalWeight < capacity:
minWt = min(weight)
val = value[weight.index(min(weight))]
totalWeight += minWt
totalValue += val
slackWt = capacity - totalWeight
'Need to fix this so it will print out the correct pick'
if totalWeight > capacity:
totalWeight-= min(weight)
totalValue -=val
print('\n__Greedy min weight __ \nItems Picked: '+ ' #' + ' #'.join(pickedItems))
print('Feasible' + '\t' + 'WeightCount:' + str(totalWeight) + '\tValueCount:' + str(totalValue) + '\n' + 'The capacity is:' + str(capacity))
return None
print('pick =' + str(weight.index(minWt)+1) + ' accumWt=' + str(totalWeight) + ' slackWt=' + str(slackWt) + ' accumVal=' + str(totalValue))
weight[weight.index(min(weight))] = 'o'
print(weight)
使用列表提取整数:
本例循环遍历
weight
列表并提取最小值。它将这个值放入min_weights
列表中。然后将找到的值更改为o
。你知道吗注意:如果存在重复的最小值,则使用
.index()
将第一个最小值替换为o
。下一次通过循环时,将找到重复项,将其添加到另一个列表中,然后更改为o
这将输出以下内容:
相关问题 更多 >
编程相关推荐