3月31日
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 = []
# 显然代码注释不应该是像我这样写的,但为了保持我的逻辑清晰没有漏洞,就多写了一点
def main():
global states_needed
global stations
while states_needed: # 当所有轴都以覆盖时结束循环
the_best_station = None
"""用来储存一轮遍历中最佳的站点,并在找出一轮最佳站点后,
重置最佳站点(否则下面的if条件无法再满足,此变量不再更新,陷入死循环)"""
covered_states = set() # 用来储存最佳站点所能覆盖的还未覆盖的洲
for station, states in stations.items(): # 遍历站点中还未成为过最佳站点过的站点
covered = states & states_needed # covered是当前遍历站点所能覆盖的未覆盖的站点的集合
if len(covered) > len(covered_states):
"""如果这个集合比目前最佳站点的覆盖集合大的话,
令它成为最佳站点,并更新covered_states"""
the_best_station = station
covered_states = covered
states_needed -= covered_states # 移除可覆盖洲
stations.pop(the_best_station) # 删除已被处理的最佳站点
final_stations.append(the_best_station) # 向最终使用站点中添加各最佳站点
print(final_stations)
if __name__ == "__main__":
main()
这篇博客写的好敷衍,害,又是被高数和物理折磨的一天,晚安