Grokking Algorithms


Same as phone_book = dict()



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

Same as phone_book = dict()
Let’s add the phone numbers of some people into this phone book:
>>> phone_book[“jenny”] = 8675309
>>> phone_book[“emergency”] = 911
That’s all there is to it! Now, suppose you want to find 
Jenny’s phone number. Just pass the key in to the hash:
>>> print phone_book[“jenny”]
8675309 
 Jenny’s phone number
Imagine if you had to do this using an array instead. 
How would you do it? Hash tables make it easy to model a relationship 
from one item to another.
Hash tables are used for lookups on a much larger scale. For example, 
suppose you go to a website like http://adit.io. Your computer has to 
translate adit.io to an IP address.


81
Use cases
For any website you go to, the address has to be translated to an IP 
address.
Wow, mapping a web address to an IP address? Sounds like a perfect 
use case for hash tables! This process is called 
DNS resolution
. Hash 
tables are one way to provide this functionality.
Preventing duplicate entries
Suppose you’re running a voting booth. Naturally, every person can 
vote just once. How do you make sure they haven’t voted before? When 
someone comes in to vote, you ask for their full name. Then you check 
it against the list of people who have voted.
If their name is on the list, this person has already voted—kick them 
out! Otherwise, you add their name to the list and let them vote. Now 
suppose a lot of people have come in to vote, and the list of people who 
have voted is really long.


82
Chapter 5
 
 
I
 
 
Hash tables
Each time someone new comes in to vote, you have to scan this giant 
list to see if they’ve already voted. But there’s a better way: use a hash!
First, make a hash to keep track of the people who have voted:
>>> voted = {}
When someone new comes in to vote, check if they’re already in
the hash:
>>> value = voted.get(“tom”)
The 
get
function returns the value if “tom” is in the hash table. 
Otherwise, it returns 
None
. You can use this to check if someone
has already voted!
Here’s the code:
voted = {}

Yüklə 348,95 Kb.

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