用Python写一个贪婪算法
时间: 2024-03-06 11:36:56 浏览: 47
Python算法教程
来解决一个背包问题,你怎么做?
可以使用以下代码实现:
def knapsack_greedy(capacity, weights, values):
n = len(weights)
ratios = [v / w for v, w in zip(values, weights)]
ratios_sorted_idx = sorted(range(n), key=lambda i: ratios[i], reverse=True)
value = 0
weight = 0
knapsack = []
for i in ratios_sorted_idx:
if weight + weights[i] <= capacity:
knapsack.append(i)
weight += weights[i]
value += values[i]
return knapsack, value
阅读全文