Grokking Algorithms



Yüklə 348,95 Kb.
Pdf görüntüsü
səhifə76/122
tarix05.12.2023
ölçüsü348,95 Kb.
#173611
1   ...   72   73   74   75   76   77   78   79   ...   122
grokking-algorithms-illustrated-programmers-curious

Calculating the answer
Now you need to calculate what stations you’ll use. Take a look 
at the image at right, and see if you can predict what stations you 
should use.
There can be more than one correct solution. You need to go 
through every station and pick the one that covers the most 
uncovered states. I’ll call this 
best_station
:
best_station = None
states_covered = set()
for station, states_for_station in stations.items():
states_covered
is a set of all the states this station covers that 
haven’t been covered yet. The 
for
loop allows you to loop over 
every station to see which one is the best station. Let’s look at the body 
of the 
for
loop:
covered = states_needed & states_for_station
if len(covered) > len(states_covered):
best_station = station
states_covered = covered
There’s a funny-looking line here:
covered = states_needed & states_for_station
What’s going on?
Sets
Suppose you have a set of fruits.
You also have a set of vegetables.
When you have two sets, you can do some fun things with them.
New syntax! This is
called a set intersection.


150
Chapter 8
 
 
I
 
 
Greedy algorithms
Here are some things you can do with sets.
• A set union means “combine both sets.”
• A set intersection means “find the items that show up in both sets”
(in this case, just the tomato).
• A set difference means “subtract the items in one set from the items
in the other set.”
For example:
>>> fruits = set([“avocado”, “tomato”, “banana”])
>>> vegetables = set([“beets”, “carrots”, “tomato”])
>>> fruits | vegetables 

Yüklə 348,95 Kb.

Dostları ilə paylaş:
1   ...   72   73   74   75   76   77   78   79   ...   122




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin