The Self-Taught Computer Scientist


Download 1.48 Mb.
Pdf ko'rish
bet109/147
Sana17.06.2023
Hajmi1.48 Mb.
#1540634
1   ...   105   106   107   108   109   110   111   112   ...   147
Bog'liq
books-library.net-11301817Az7X6

Figure 13.5: Hash table operation run times


Chapter 13 Hash Tables
141
As a programmer, you will frequently use hash tables. For example, if you are a web developer, you 
will often work with JavaScript Object Notation (JSON), a data- interchange format. Many APIs send 
data in JSON, which you can easily turn into a Python dictionary. An application programming inter-
face (API) is a program that allows applications to communicate with each other. Any time you work 
with a key- value database in Python, you will use dictionaries. The popular version control system 
Git uses the hash values from a cryptographic hash function to store different versions of the data in 
your projects. Operating systems often use hash tables to help manage memory. Python itself uses 
dictionaries (hash tables) to hold object variable names and values.
You should consider using a hash table whenever you have a large amount of data and you need to 
access individual data items quickly. For example, suppose you were writing a program that needed 
to search the English dictionary or you wanted to create an app that requires fast access to anyone’s 
phone number in a phone book with hundreds of thousands or millions of entries. Hash tables are 
appropriate for either of these situations. Generally, they are a suitable data structure to use anytime 
you need fast, random access to data. However, if you were frequently operating on the data in sequen-
tial order, an array or a linked list might be a better choice.
Characters in a String
When you solve a problem, it is helpful to think about using a hash table in your solution because they 
are so efficient. For example, suppose an interviewer asks you to count all the characters in a string. 
One solution to this problem is to use a Python dictionary. You can store each character as a key in 
your dictionary and the number of times it occurs in the string as a value. Here is how it works:
def count(a_string):
a_dict = {}
for char in a_string:
if char in a_dict:
a_dict[char] += 1
else:
a_dict[char] = 1
print(a_dict)
Your function
count
, accepts a string as a parameter (the string you want to count the characters of):
def count(a_string):
Inside your function, you create a dictionary:
a_dict = {}
Next, you use a 
for
loop to iterate through your string:
for char in a_string:



Download 1.48 Mb.

Do'stlaringiz bilan baham:
1   ...   105   106   107   108   109   110   111   112   ...   147




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling