Menu

[solved]-Given Array Queue Code Class Arrayqueue Initialcapacity 8 Def Init Self Use List Store Que Q39046934

Stacks with Queues 3 In this problem, try to implement a stack using a queue. Write a class called class QStack that has implor raise an Exception if the stack is empty def top(self) Returns (without removing) the element at the top of the stack

Here is the given Array Queue code:

class ArrayQueue:
INITIAL_CAPACITY = 8
  
def __init__(self):
# Use a list to store queue elements
# self.data is the list used to store elements
# len(self.data) is our capacity (how many elements we can storebefore resizing
# self.num_of_elems is the number of elements in the queue
# self.front_ind will be the index of the “front” of the queue (thefirst element to have been inserted
self.data = [None] * ArrayQueue.INITIAL_CAPACITY
self.num_of_elems = 0
self.front_ind = None

# O(1) time
def __len__(self):
# len(self) is the number of elements in the queue ==self.num_of_elems
return self.num_of_elems

# O(1) time
def is_empty(self):
# Queue is empty if it has no elements (len is 0)
return len(self) == 0

# Amortized worst case running time is O(1)
# But an individual enqueue can take worst case O(n) if resize isdone
# This time complexity is just like the append operation in dynamicarrays

def enqueue(self, elem):
# If number of elements == capacity (we’ve filled the listcompletely), resize
if self.num_of_elems == len(self.data):
self.resize(2 * len(self.data))
  
# If list was empty before trying to enqueue `elem`,
# Put it at index 0 at set the front_ind to 0 (since this is thefirst elem in the queue)

if self.is_empty():
self.data[0] = elem
self.front_ind = 0
self.num_of_elems += 1
# Otherwise, if the queue already had elements

else:
back_ind = (self.front_ind + self.num_of_elems) %len(self.data)
self.data[back_ind] = elem
self.num_of_elems += 1

# Amortized worst case running time of O(1)
# But, an individual dequeue might cause a resize with running timeO(n)
# The time complexity is just like pop in dynamic arrays

def dequeue(self):
# Raise an exception if the queue is empty (we can’t remove from anempty queue!)
if self.is_empty():
raise Exception(“Queue is empty”)
# Get the elem at the front of the queue
# Then set the front to None so that it is “reset”
elem = self.data[self.front_ind]
self.data[self.front_ind] = None

if self.is_empty():
self.front_ind = None
# As with dynamic arrays, we shrink the underlying array (by half)if we are using less than 1/4 of the capacity
elif len(self) < len(self.data) // 4:
self.resize(len(self.data) // 2)
return elem

# O(1) running time
def first(self):
# The first element in the queue is at the “front” index
# But we raise an error if the queue is empty
if self.is_empty():
raise Exception(“Queue is empty”)
return self.data[self.front_ind]

# Resizing takes time O(n) where n is the number of elements inthe queue

def resize(self, new_capacity):
# Create new array of size new_capacity, and copy elements to newarray
old_data = self.data
self.data = [None] * new_capaacity
# The “front” of the old array is at front_ind. We will startcopying from the front.
old_ind = self.front_ind
for new_ind in range(self.num_of_elems):
# We copy from the old array starting at the front, to index 0 inthe new array
# In the new array, the “front” will be at index 0
self.data[new_ind] = old_data[old_ind]
old_ind = (old_ind + 1) % len(old_data)
# Update the front — it is now at index 0
self.front_ind = 0

cla se t.data ia the list used to store elecents a LUze eLuze esizine al t. tron 1n t the mcne (the tirat clement to have bee

Stacks with Queues 3 In this problem, try to implement a stack using a queue. Write a class called class QStack that has implements the stack ADT. It should have an instance of the class ArrayQueue as a data member (use the ArrayQueue class we wrote in lecture – you can get the code from NYU Classes). You can only access and modify this ArrayQueue instance by using the methods that are defined as part of the ArrayQueue class (that is, the methods that make up the interface of the Queue ADT). Your QStack class may also use O(1) additional space for other data members as necessary (this is a constant amount of extra spaceso you may not include extra data structures or collections of non-constant size) Recall that as the QStack will implement the Stack ADT, you must define all the operations of the Stack ADT. A skeleton of the class along with the methods you must implement is below: class QStack: def_init__ (self, max_num_of_elems) Initialize an empty leaky stack” self.data queue = Array Queue ( # You may need to add to this cons tructor, such as adding more data memb ers # But you should at minimum have the ArrayQueue data member as above def len__(self) Return the number of elements in the stack’ ‘ ‘ def is_empty (self) ‘Returns True if the stack is empty’ def push(self, elem) Adds elem to the top of the stack” def pop(self) Remove and return the element at the t op of the stack or raise an Exception if the stack is empty’ ” def top(self) ‘Returns (without removing) the element at the top of the stack or raise an Exception if the stack is empty”’ Hint: You will not be able to achieve O(1) worst-case running times for all operations. In fact, some operations may be very inefficient. That is okay: There is no running time requirement for this problem (however, see below). Analyze the running time of the operations in your implementation, particularly push and pop. In the code you submit, include the running time of each of your operations in a comment at the top of each method’s implementation. While there is no requirement for efficiency, you must analyze the running times and include them in your submission for full credit Also think about, but don’t submit: Which of the operations, push or pop, is more efficient in your implementation? If your pop is more efficient, can you think of an alternate implementation where push would be more efficient (possibly at the expense of making pop less efficient)? If your push is more efficient, can you think of an alternate implementation where pop would be more efficient (at the expense of making push more expensive)? cla se t.data ia the list used to store elecents a LUze eLuze esizine al t. tron 1n t the mcne (the tirat clement to have been inaart ad) 1 hr the 1ndex of thr “tront” of elm YQu .IETIA CAACITY nol f. front Tnd Non ber of clamcnt i he qinue nelf.muof lamn return aelt.pum ot elema. 1Lme dof in entycl f): has no eementa ler s B an 1nd1v14a enTene can take worat gane tn ir resize ia Tis Le Lexily ie ju ike Lhe dpuend operaLion i dyia aLLav clc-ne If nrher of clement apacity (w’vo filled the liat aomoletel y), roniz t nd at he tront sne o ia1rce thia is the tirst eLe in the cuee l zelf.la py lt erwlee, i Lhe ueue already liad elemenLe ineL t.cota .k 1n- tn Bel.u of elem f Amertized worst caae running time ot O(1n D..L, a individual deque ne migt cause a esize withuin Li ta fTh i-e complex Ly j 1ike op in dynami array daf ovcont: o Teue is eupty ( can’t remove trom an empty queuel he Get the c1 em at the frant of thc qicne Then et that it is “reaet” Show transcribed image text Stacks with Queues 3 In this problem, try to implement a stack using a queue. Write a class called class QStack that has implements the stack ADT. It should have an instance of the class ArrayQueue as a data member (use the ArrayQueue class we wrote in lecture – you can get the code from NYU Classes). You can only access and modify this ArrayQueue instance by using the methods that are defined as part of the ArrayQueue class (that is, the methods that make up the interface of the Queue ADT). Your QStack class may also use O(1) additional space for other data members as necessary (this is a constant amount of extra spaceso you may not include extra data structures or collections of non-constant size) Recall that as the QStack will implement the Stack ADT, you must define all the operations of the Stack ADT. A skeleton of the class along with the methods you must implement is below: class QStack: def_init__ (self, max_num_of_elems) Initialize an empty leaky stack” self.data queue = Array Queue ( # You may need to add to this cons tructor, such as adding more data memb ers # But you should at minimum have the ArrayQueue data member as above def len__(self) Return the number of elements in the stack’ ‘ ‘ def is_empty (self) ‘Returns True if the stack is empty’ def push(self, elem) Adds elem to the top of the stack” def pop(self) Remove and return the element at the t op of the stack
or raise an Exception if the stack is empty’ ” def top(self) ‘Returns (without removing) the element at the top of the stack or raise an Exception if the stack is empty”’ Hint: You will not be able to achieve O(1) worst-case running times for all operations. In fact, some operations may be very inefficient. That is okay: There is no running time requirement for this problem (however, see below). Analyze the running time of the operations in your implementation, particularly push and pop. In the code you submit, include the running time of each of your operations in a comment at the top of each method’s implementation. While there is no requirement for efficiency, you must analyze the running times and include them in your submission for full credit Also think about, but don’t submit: Which of the operations, push or pop, is more efficient in your implementation? If your pop is more efficient, can you think of an alternate implementation where push would be more efficient (possibly at the expense of making pop less efficient)? If your push is more efficient, can you think of an alternate implementation where pop would be more efficient (at the expense of making push more expensive)?
cla se t.data ia the list used to store elecents a LUze eLuze esizine al t. tron 1n t the mcne (the tirat clement to have been inaart ad) 1 hr the 1ndex of thr “tront” of elm YQu .IETIA CAACITY nol f. front Tnd Non ber of clamcnt i he qinue nelf.muof lamn return aelt.pum ot elema. 1Lme dof in entycl f): has no eementa ler s B an 1nd1v14a enTene can take worat gane tn ir resize ia Tis Le Lexily ie ju ike Lhe dpuend operaLion i dyia aLLav clc-ne If nrher of clement apacity (w’vo filled the liat aomoletel y), roniz t nd at he tront sne o ia1rce thia is the tirst eLe in the cuee l zelf.la py lt erwlee, i Lhe ueue already liad elemenLe ineL t.cota .k 1n- tn Bel.u of elem f Amertized worst caae running time ot O(1n D..L, a individual deque ne migt cause a esize withuin Li ta fTh i-e complex Ly j 1ike op in dynami array daf ovcont: o Teue is eupty ( can’t remove trom an empty queuel he Get the c1 em at the frant of thc qicne Then et that it is “reaet”

Expert Answer


Answer to Here is the given Array Queue code: class ArrayQueue: INITIAL_CAPACITY = 8 def __init__(self): # Use a list to store qu… . . .

OR


Leave a Reply

Your email address will not be published. Required fields are marked *