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 = {}
Dostları ilə paylaş: