Greedy algorithm implemented in Python

# Use Python to achieve greedy algorithm 
# set covering problem
# Suppose you do a radio show, to make the nation's 50 states listeners are listening to. To do this, you need to decide which aired on broadcast stations. Broadcast in each broadcast station would need to pay for it, so you tried to radio station in as little broadcast # 1. Create a list that contains to be covered by the state states_needed = the SET ([ "MT", "WA", "or", "the above mentioned id", "nv", "UT", "CA", "az"]) # 2. use hash table represent alternative radio station list stations = dict () stations [ "KONE"] = SET ([ "ID", "NV", "UT"]) Stations [ "ktwo"] = SET ([ "WA", "



"NV", "CA"]) Stations [ "kfour"] = SET ([ "NV", "UT"]) Stations [ "kfive"] = SET ([ "CA", "AZ"])
#. 3. used to store the final set of selected broadcast station
final_stations =
sET ()
# 5. the cycle
the while states_needed:
# through all broadcast stations, covering most select uncovered state broadcasting station, the broadcast station is stored in the best_station the
best_station = none
# all states not covered by this set contains the broadcast station coverage
states_covered = the SET ()
for station, States in stations. items ():
covered's = states_needed States &
IF len (covered's)>len(states_covered):
best_station = station
states_covered = covered

states_needed -= states_covered
final_stations.
add(best_station)

print(final_stations) # 结果为{'ktwo', 'kthree', 'kone', 'kfive'}

Guess you like

Origin www.cnblogs.com/lty-fly/p/11713955.html