mirror of
https://github.com/onyx-and-iris/grokking-algorithms.git
synced 2025-01-18 00:30:53 +00:00
add greedy
This commit is contained in:
parent
710f54a44e
commit
e36f91c094
44
chapter10/greedy.py
Normal file
44
chapter10/greedy.py
Normal file
@ -0,0 +1,44 @@
|
||||
import logging
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
stations = {
|
||||
"kone": set(["id", "nv", "ut"]),
|
||||
"ktwo": set(["wa", "id", "mt"]),
|
||||
"kthree": set(["or", "nv", "ca"]),
|
||||
"kfour": set(["nv", "ut"]),
|
||||
"kfive": set(["ca", "az"]),
|
||||
}
|
||||
|
||||
|
||||
def greedy():
|
||||
def fget():
|
||||
needed = set()
|
||||
for states in stations.values():
|
||||
needed |= states
|
||||
return needed
|
||||
|
||||
states_needed = fget()
|
||||
logger.debug(states_needed)
|
||||
|
||||
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)
|
||||
|
||||
return final_stations
|
||||
|
||||
|
||||
final_stations = greedy()
|
||||
print(f"final stations greedy approximation: {final_stations}")
|
Loading…
Reference in New Issue
Block a user