Grokking Algorithms


def check_voter(name): if



Yüklə 348,95 Kb.
Pdf görüntüsü
səhifə46/122
tarix05.12.2023
ölçüsü348,95 Kb.
#173611
1   ...   42   43   44   45   46   47   48   49   ...   122
grokking-algorithms-illustrated-programmers-curious

def check_voter(name):
if voted.get(name):
print “kick them out!”
 else:
voted[name] = True
print “let them vote!”
Let’s test it a few times:
>>> check_voter(“tom”)
let them vote!
>>> check_voter(“mike”)
let them vote!
>>> check_voter(“mike”)
kick them out!
The first time Tom goes in, this will print, “let them vote!” Then Mike 
goes in, and it prints, “let them vote!” Then Mike tries to go a second 
time, and it prints, “kick them out!”


83
Use cases
Remember, if you were storing these names in a list of people who have 
voted, this function would eventually become really slow, because it 
would have to run a simple search over the entire list. But you’re storing 
their names in a hash table instead, and a hash table instantly tells you 
whether this person’s name is in the hash table or not. Checking for 
duplicates is very fast with a hash table.
Using hash tables as a cache
One final use case: caching. If you work on a website, you 
may have heard of caching before as a good thing to do. 
Here’s the idea. Suppose you visit facebook.com:
1. You make a request to Facebook’s server.
2. The server thinks for a second and comes up with
the web page to send to you.
3. You get a web page.
For example, on Facebook, the server may be collecting all of your 
friends’ activity to show you. It takes a couple of seconds to collect all 
that activity and shows it to you. That couple of seconds can feel like a 
long time as a user. You might think, “Why is Facebook being so slow?” 
On the other hand, Facebook’s servers have to serve millions of people
and that couple of seconds adds up for them. Facebook’s servers are 
really working hard to serve all of those websites. Is there a way to make 
Facebook faster and have its servers do less work at the same time?
Suppose you have a niece who keeps asking you about planets. “How far 
is Mars from Earth?” “How far is the Moon?” “How far is Jupiter?” Each 
time, you have to do a Google search and give her an answer. It takes 


84

Yüklə 348,95 Kb.

Dostları ilə paylaş:
1   ...   42   43   44   45   46   47   48   49   ...   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