The Self-Taught Computer Scientist


Download 1.48 Mb.
Pdf ko'rish
bet105/147
Sana17.06.2023
Hajmi1.48 Mb.
#1540634
1   ...   101   102   103   104   105   106   107   108   ...   147
Bog'liq
books-library.net-11301817Az7X6

Data Structures
136
Now that you’ve defined 
enqueue
, you create a method called 
dequeue
to remove an item from 
your queue:
def dequeue(self):
if len(self.s1) == 0:
raise Exception("Cannot pop from empty queue")
return self.s1.pop()
First, you check to see whether 
self.s1
is empty. If it is, it means the user is trying to 
dequeue
an 
item from an empty queue, so you raise an exception:
if len(self.s1) == 0:
raise Exception("Cannot pop from empty queue")
Otherwise, you pop the item at the front of your first stack and return it:
return self.s1.pop() 
In this implementation of a queue, enqueueing is O(
n) because you have to iterate through every 
item in your stack. Dequeueing, on the other hand, is O(1) because you have to remove only the last 
item from your internal stack.
Vocabulary
queue: A linear data structure similar to a stack.
first- in, first- out data structure: A data structure where the first item to enter the data structure is 
the first to come out of it.
enqueueing: Adding an item to a queue.
dequeueing: Removing an item from a queue.
bounded queue: A queue that limits how many items you can add to it.
unbounded queue: A queue that does not limit how many items you can add to it.
Challenge
1. 
Implement a queue using two stacks, but make enqueueing O(1).


13
Hash Tables
For self- educated scientists and thinkers such as Charles Darwin, Srinivasa Ramanujan
Leonardo da Vinci, Michael Faraday, myself, and many others, education is a relentless voy-
age of discovery. To us, education is an everlasting quest for knowledge and wisdom.
Abhijit Naskar
An associative array is an abstract data type that stores key- value pairs with unique keys. A key- 

Download 1.48 Mb.

Do'stlaringiz bilan baham:
1   ...   101   102   103   104   105   106   107   108   ...   147




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