From 26aa694fbcee0acc13a254fa5e1b115251bfde73 Mon Sep 17 00:00:00 2001 From: Aditya Bhargava Date: Wed, 2 Mar 2016 15:05:49 -0800 Subject: [PATCH] code for chapter 8 --- .../python/01_set_covering.py | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 08_greedy_algorithms/python/01_set_covering.py diff --git a/08_greedy_algorithms/python/01_set_covering.py b/08_greedy_algorithms/python/01_set_covering.py new file mode 100644 index 0000000..e447857 --- /dev/null +++ b/08_greedy_algorithms/python/01_set_covering.py @@ -0,0 +1,25 @@ +# You pass an array in, and it gets converted to a set. +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