写一个贪心算法的Python代码案例
时间: 2023-03-10 10:16:52 浏览: 114
def greedyAlgorithm(values, weights, capacity):
# initialize total value and weight of knapsack to 0
totalValue = 0
totalWeight = 0
# loop through all items
for i in range(len(values)):
# if adding current item doesn't exceed capacity
if totalWeight + weights[i] <= capacity:
# add current item to the knapsack
totalWeight += weights[i]
totalValue += values[i]
# return total value of knapsack
return totalValue
# values of items
values = [60, 100, 120]
# weights of items
weights = [10, 20, 30]
# capacity of knapsack
capacity = 50
# call greedy algorithm function
print(greedyAlgorithm(values, weights, capacity))
阅读全文