class QStack: def __init__(self): self.data = ArrayQueue() def __len__(self): return len(self.data) def is_empty(self): return len(self) == 0 def push(self, elem): #O(1) self.data.enqueue(elem) def pop(self): #O(n) if self.is_empty(): raise Exception("The QStack is empty") helper = ArrayQueue() for i in range(len(self) - 1): helper.enqueue(self.data.dequeue()) val = self.data.dequeue() self.data = helper return val def top(self): #O(n) if self.is_empty(): raise Exception("The QStack is empty") helper = ArrayQueue() for i in range(len(self)): val = self.data.dequeue() helper.enqueue(val) self.data = helper return val
def test_pop(self): """ pop once """ test = ArrayQueue() test.push(1) test.push(2) popped = test.pop() self.assertEqual(popped, 1)
def top(self): #O(n) if self.is_empty(): raise Exception("The QStack is empty") helper = ArrayQueue() for i in range(len(self)): val = self.data.dequeue() helper.enqueue(val) self.data = helper return val
def print_tree(self): q = ArrayQueue() q.enqueue(self.root) while not q.empty(): n = q.dequeue() print('[k: ' + str(n.key) + ', v: ' + str(n.value) + ']') if n.left is not None: q.enqueue(n.left) if n.right is not None: q.enqueue(n.right)
def breadth_first(self): if (self.is_empty()): return line = ArrayQueue() line.enqueue(self.root) while (line.is_empty() == False): curr_node = line.dequeue() yield curr_node if (curr_node.left is not None): line.enqueue(curr_node.left) if (curr_node.right is not None): line.enqueue(curr_node.right)
def test_popAll(self): """ pop all elements""" test = ArrayQueue() test.push(1) test.push(2) test.push(3) test.push(4) test.pop() test.pop() test.pop() test.pop() self.assertEqual(test.show_array, [None, None, None, None, None, None, None, None, None, None])
def __init__(self): self._priority_queue = LinkedQueue() self._queue = ArrayQueue() self._current_plane = None self._total_plane_wait_time = 0 self._planes_served = 0 self._planes_crashed = 0 self._metrics = { "longest_wait_takeoff": 0, "longest_wait_landing": 0, "served_takeoff": 0, "served_landing": 0 }
def invert_binary_tree2(root): if (root is None): return line = ArrayQueue() line.enqueue(root) while (line.is_empty() == False): curr_node = line.dequeue() curr_node.left, curr_node.right \ = curr_node.right, curr_node.left if (curr_node.left is not None): line.enqueue(curr_node.left) if (curr_node.right is not None): line.enqueue(curr_node.right)
def test_ArrayQueue(): s = ArrayQueue() print(s.empty()) for i in range(33): s.enqueue(i) print('loop', i) print(s.front()) s.print()
def breadth_first_print(self): Q = ArrayQueue() Q.enqueue(self.root()) while not Q.is_empty(): p = Q.dequeue() print(p) for c in self.children(p): Q.enqueue(c)
def test_clear(self): test = ArrayQueue() test.push(1) test.push(2) test.push(3) self.assertEqual(test.show_array, [1, 2, 3, None, None, None, None, None, None, None]) test.clear() self.assertEqual(test.show_array, [None, None, None, None, None, None, None, None, None, None])
def breath_first(self): from ArrayQueue import ArrayQueue fringe = ArrayQueue() fringe.enqueue(self.root()) while not fringe.is_empty(): p = fringe.dequeue() yield p for c in p.children(): fringe.enqueue(c)
def test_randomForFun(self): """random push/pops v.3, just making sure""" test = ArrayQueue() for i in range(1, 11): test.push(i) test.pop() test.pop() test.push('a') self.assertEqual(test.show_array, ['a', None, 3, 4, 5, 6, 7, 8, 9, 10])
def test_random(self): """random push/pops""" test = ArrayQueue() for i in range(1, 11): test.push(i) for i in range(1, 11): test.pop() test.push('a') test.push('b') self.assertEqual(test.show_array, ['a', 'b', None, None, None, None, None, None, None, None])
def permutations(lst): perms = ArrayStack() parts = ArrayQueue() combo = [] for x in range(len(lst)): if perms.is_empty(): perms.push([lst[x]]) else: for y in range(len(perms)): p_lst = perms.pop() for z in range(len(p_lst) + 1): parts.enqueue(p_lst[:z] + [lst[x]] + p_lst[z:]) for a in range(len(parts)): perms.push(parts.dequeue()) while not perms.is_empty(): combo.append(perms.pop()) return combo
class CheckoutManager(object): """CheckoutManager object for handling a collection of checkout queues that process customers.'""" def __init__(self, n_checkouts, checkout_capacity, staging_capacity): self.checkouts = [ArrayQueue(checkout_capacity) for _ in xrange(n_checkouts)] self.staging_queue = ArrayQueue(staging_capacity) self.finished_customers = [] def enqueue_random(self, customer): """Adds the given customer to a random checkout.""" checkout = random.choice(self.checkouts) customer.queue(checkout) def enqueue_shortest(self, customer): """Adds the given customer to the checkout with the shortest queue.""" checkout = min(self.checkouts, key=len) customer.queue(checkout) def enqueue_staging(self, customer): """Adds the customer to a staging queue. The customer will move from the staging queue to an empty checkout as one becomes available.""" customer.queue(self.staging_queue) def has_item(self): """Checks if any checkout has a customer in it, or if the staging queue has a customer in it.""" for checkout in self.checkouts: if checkout.has_item(): return True return False def update(self): """Called once per game cycle.""" for checkout in self.checkouts: if checkout.has_item(): if checkout[0].checked_out(): # remove finished customer customer = checkout.dequeue() customer.leave() if checkout.empty() and self.staging_queue.has_item(): # add waiting customer customer = self.staging_queue.dequeue() customer.queue(checkout) if checkout.has_item(): checkout[0].checkout() # checkout front customer
def is_complete(root): if (root is None): return True line = ArrayQueue() line.enqueue(root) level = 0 while (line.is_empty() == False): if (len(line) != 2**level): return False for i in range(2**level): curr_node = line.dequeue() if (curr_node.left is not None): line.enqueue(curr_node.left) if (curr_node.right is not None): line.enqueue(curr_node.right) level += 1 return True
def __str__(self): str_return = '' q_uttt = ArrayQueue() q_uttt.enqueue(self._root) last_depth = 0 while not q_uttt.is_empty(): child = q_uttt.dequeue() if last_depth != child.get_depth(): str_return += "\n" str_return += child.get_meta().get_meta_int() + ' ' last_depth = child.get_depth() for grand_child in child.get_children(): q_uttt.enqueue(grand_child) return str_return
def test_expandWhenFull(self): """when size of array is at capacity, double array""" test = ArrayQueue() for i in range(1, 11): test.push(i) self.assertEqual(test.show_array, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) test.push(11) self.assertEqual(test.show_array, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, None, None, None, None, None, None, None, None, None])
def print_tree_level(bin_Tree, level): output = [] if (bin_Tree.is_empty()): return line = ArrayQueue() line.enqueue((bin_Tree.root, 0)) while (line.is_empty() == False): curr = line.dequeue() output.append(curr) depth = curr[1] if (curr[0].left is not None): line.enqueue((curr[0].left, depth + 1)) if (curr[0].right is not None): line.enqueue((curr[0].right, depth + 1)) i = 0 outputlst = [] for i in output: if i[1] == level: outputlst.append(i[0].data) print(outputlst)
def bfs(self, r: int): seen = np.zeros(self.n, np.bool_) l = [] q = ArrayQueue() q.add(r) seen[r] = True while q.size() > 0: i = q.remove() l.append(i) ngh = self.out_edges(i) for k in range(0, ngh.size()): j = ngh.get(k) if seen[j] == False: q.add(j) seen[j] = True return l
class Company: def __init__(self): self._actions = ArrayQueue() def buy(self, quantity, price): self._actions.enqueue(Sale(quantity, price)) def sell(self, quantity, price): gain = 0 while quantity > 0: latest = self._actions.first() if latest.qua <= quantity: gain += latest.qua * (price - latest.price) quantity -= latest.qua self._actions.dequeue() else: gain += quantity * (price - latest.price) latest.qua -= quantity quantity = 0 return gain def __str__(self): return str(self._actions._data)
class MeanQueue: def __init__(self): self.data = ArrayQueue() def __len__(self): return len(self.data) def is_empty(self): return len(self.data) == 0 def enqueue(self, e): if not isinstance(e, (int, float)): raise TypeError("Item must be int or float type!") self.data.enqueue(e) def dequeue(self): if self.is_empty(): raise Exception("MeanQueue is empty!") return self.data.dequeue() def first(self): if self.is_empty(): raise Exception("MeanQueue is empty!") return self.data.first() def sum(self): total = 0 for i in range(len(self)): total += self.data.first() self.data.enqueue(self.data.dequeue()) return total def mean(self): return self.sum() / len(self)
detailed_mode = False filepath = None if (len(sys.argv) == 3): if sys.argv[1] == '--verbose': detailed_mode = True filepath = sys.argv[2] elif (len(sys.argv) == 2): filepath = sys.argv[1] unsorted_jobs_lst = [] random_num_ind = 0 random_num_lst = loadRamdomNum() jobs_lst = read_jobs(filepath) Q = ArrayQueue() cpu_can_run = True job_incomplete = len(jobs_lst) time = 0 run_lst = [] block_lst = [] job_is_running_time = 0 # to calc cpu utilization job_is_blocking_time = 0 # to calc i/o utilization if detailed_mode: print( "\nThis detailed printout gives the state and remaining burst for each process.\n" ) while job_incomplete > 0: # one time unit is one cycle if detailed_mode: cycle_report(time, jobs_lst)
def permutations(lst): stack = ArrayStack() queue = ArrayQueue() for val in lst: queue.enqueue([val]) while (len(lst) != len(queue.first())): for integer in lst: if integer not in queue.first(): stack.push([integer]) for i in range(len(stack)): queue.enqueue(queue.first() + stack.pop()) queue.dequeue() while queue.is_empty == False: permuations_array.append(q.dequeue()) return permuations_array
def __init__(self, n_checkouts, checkout_capacity, staging_capacity): self.checkouts = [ArrayQueue(checkout_capacity) for _ in xrange(n_checkouts)] self.staging_queue = ArrayQueue(staging_capacity) self.finished_customers = []
def __init__(self): self.data = ArrayQueue()
def __init__(self): ArrayQueue.__init__(self)
def __init__(self): self._actions = ArrayQueue()
class Tower: def __init__(self): self._priority_queue = LinkedQueue() self._queue = ArrayQueue() self._current_plane = None self._total_plane_wait_time = 0 self._planes_served = 0 self._planes_crashed = 0 self._metrics = { "longest_wait_takeoff": 0, "longest_wait_landing": 0, "served_takeoff": 0, "served_landing": 0 } def add_to_Q(self, c): self._queue.add(c) def add_to_PriorityQ(self, c): self._priority_queue.add(c) def set_metrics(self, plane, cur_time): """ set class' metrics :param plane: :param cur_time: """ if plane is not None: #check takeoff metrics if plane.status == "Takeoff": wait_time = cur_time - self._current_plane.arrival_time self._metrics["longest_wait_takeoff"] += wait_time if wait_time > self._metrics["longest_wait_takeoff"]: self._metrics["longest_wait_takeoff"] = wait_time #check landing metrics if plane.status == "Landing": wait_time = cur_time - self._current_plane.arrival_time self._metrics["longest_wait_landing"] += wait_time if wait_time > self._metrics["longest_wait_landing"]: self._metrics["longest_wait_landing"] = wait_time def check_if_complete(self, plane): if plane is not None: #if plane is complete if plane.transaction_time == 0: if plane.status == "Takeoff": self._metrics["served_takeoff"] += 1 else: self._metrics["served_landing"] += 1 self._current_plane = None self._planes_served += 1 def serve_plane(self, cur_time): """ :param curr_time: int clock_tick """ if self._current_plane is None: # No plane is being helped and queue is empty, do nothing if self._queue.is_empty() and self._priority_queue.is_empty(): return else: # set the planes try: if len(self._priority_queue) > 0: self._current_plane = self._priority_queue.pop() self._current_plane.minus_fuel() # crashed plane if self._current_plane.fuel == 0: self._current_plane = None self._planes_crashed += 1 else: if self._queue.peek() is not None: self._current_plane = self._queue.pop() except: pass self.set_metrics(self._current_plane, cur_time) if self._current_plane is not None: self._current_plane.serve() self.check_if_complete(self._current_plane) @property def queue(self): return self._queue @property def priority_queue(self): return self._priority_queue def __str__(self): return_string = "\naverage time spent waiting for take off: " + str( self._metrics["longest_wait_takeoff"] / (round(self._metrics["served_takeoff"] + 1, 3))) return_string += "\naverage time spent waiting for to land: " + str( self._metrics["longest_wait_landing"] / round(self._metrics["served_landing"] + 1, 3)) return_string += "\nlongest time spent waiting for take off: " + str( self._metrics["longest_wait_takeoff"]) return_string += "\nlongest time spent waiting for to land: " + str( self._metrics["longest_wait_landing"]) return_string += "\nPlanes Crashed: " + str(self._planes_crashed) return_string += "\nPlanes served: " + str(self._planes_served) return_string += f"\nPlanes in queues {len(self._priority_queue) + len(self._queue)}" return return_string # What is the average time spent waiting for take off? # What is the average time spent waiting to land? # What is the longest time spent waiting for take off? # What is the longest time spent waiting to land? # How many planes crashed? # print(f"{len(tower.priority_queue)} {len(tower.queue)}") # How many planes total took off and landed during the simulation?
from ArrayQueue import ArrayQueue from LoopQueue import LoopQueue from time import time from random import randint def test_enqueue(queue, op_count): start_time = time() for i in range(op_count): queue.enqueue(randint(1, 2000)) return time() - start_time def test_dequeue(queue, op_count): start_time = time() for i in range(op_count): queue.dequeue() return time() - start_time op_count = 10000 array_queue = ArrayQueue() loop_queue = LoopQueue() print('ArrayQueue enqueue: ', test_enqueue(array_queue, op_count)) print('LoopQueue enqueue: ', test_enqueue(loop_queue, op_count)) print('ArrayQueue dequeue: ', test_dequeue(array_queue, op_count)) print('LoopQueue dequeue: ', test_dequeue(loop_queue, op_count))
def setUp(self): self.queues = [] self.queues.append(LinkedQueue()) self.queues.append(ArrayQueue(0, 3)) self.queues.append(IntQueue(2))