1. 程式人生 > >Python貪婪算法

Python貪婪算法

ems 情況下 最優 final clas none ive pre stat

貪婪算法

  • 每步均選擇局部的最優解,重復此過程,最終即得到全局的最優解
  • 簡而言之就是每步都采用最優解

優點:

  • 簡單易行

缺點:

  • 並非在所有情況下都奏效

經典的問題:

  1. 背包問題
  2. 集合覆蓋問題

貪婪算法下的近似算法解決集合覆蓋問題

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貪婪算法