Python贪婪算法
Posted YC的技术笔记
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python贪婪算法相关的知识,希望对你有一定的参考价值。
贪婪算法
- 每步均选择局部的最优解,重复此过程,最终即得到全局的最优解
- 简而言之就是每步都采用最优解
优点:
- 简单易行
缺点:
- 并非在所有情况下都奏效
经典的问题:
- 背包问题
- 集合覆盖问题
贪婪算法下的近似算法解决集合覆盖问题
states_needed = set(["mt", "wa", "or", "id", "nv", "ut", "ca", "az"])
stations = {}
stations["kone"] = set(["id", "nv", "ut"])
stations["ktwo"] = set(["wa", "id", "mt"])
stations["kthree"] = set(["or", "nv", "ca"])
stations["kfour"] = set(["nv", "ut"])
stations["kfive"] = set(["ca", "az"])
final_stations = set()
while states_needed:
best_station = None
states_covered = set()
for station, states in stations.items():
covered = states_needed & states
if len(covered) > len(states_covered):
best_station = station
states_covered = covered
states_needed -= states_covered
final_stations.add(best_station)
print(final_stations)
以上是关于Python贪婪算法的主要内容,如果未能解决你的问题,请参考以下文章