def test_get_size(): queue = Queue() assert queue.get_size() == 0 queue.enqueue(1) assert queue.get_size() == 1 queue.dequeue() assert queue.get_size() == 0
def test_enqueue(): queue = Queue() queue.enqueue(1) queue.enqueue(2) assert queue.head.value == 2 assert queue.tail.value == 1
def test_has_limit(): queue = Queue(1) assert queue.has_space() is True assert queue.limit == 1 queue.enqueue(1) assert queue.has_space() is False with pytest.raises(QueueIsFull): queue.enqueue(2)
def hot_potato(name_list, num): simqueue = Queue() for name in name_list: simqueue.enqueue(name) while simqueue.size > 1: for _ in range(num - 1): simqueue.enqueue(simqueue.dequeue()) simqueue.dequeue() return simqueue.dequeue()
def hot_potato(name_lst, num): q = Queue() for n in name_lst: q.enqueue(n) while q.size() > 1: for i in range(num): q.enqueue(q.dequeue()) q.dequeue() return q.dequeue()
def queue_reverser(queue): new_queue = Queue() stack = Stack() length = queue.length for _ in range(length): item = queue.dequeue() stack.push(item) queue.enqueue(item) for _ in range(length): new_queue.enqueue(stack.pop()) return new_queue
def test_front(self): q = Queue() assert q.front() is None q.enqueue('A') assert q.front() == 'A' q.enqueue('B') assert q.front() == 'A' q.dequeue() assert q.front() == 'B' q.dequeue() assert q.front() is None
def test_length(self): q = Queue() assert q.length() == 0 q.enqueue('A') assert q.length() == 1 q.enqueue('B') assert q.length() == 2 q.dequeue() assert q.length() == 1 q.dequeue() assert q.length() == 0
def test_dequeue(): queue = Queue() queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) assert queue.dequeue() == 1 assert queue.head.value == 3 assert queue.tail.value == 2 queue.dequeue() assert queue.dequeue() == 3 assert queue.head is None assert queue.tail is None
def breadth_first_search_adjlist(graph, source, destination): if not source in graph.vertices: print('Source does not exist in graph') return if not destination in graph.vertices: print('destination does not exist in graph') return #Set inital parameters for source vert, enqueue source graph.vertex_object[source].color = 'grey' graph.vertex_object[source].distance = 0 graph.vertex_object[source].prev_search = None bfs_queue = Queue() bfs_queue.enqueue(source) #BFS while loop. Search closest nodes and set distances from source/build tree while not bfs_queue.is_empty(): current_vert = graph.vertex_object[bfs_queue.dequeue()] print(current_vert.name) for vertex in graph.vertices[current_vert.name]: if graph.vertex_object[vertex].color == 'white': graph.vertex_object[vertex].color = 'grey' graph.vertex_object[ vertex].distance = current_vert.distance + 1 graph.vertex_object[vertex].prev_search = current_vert.name bfs_queue.enqueue(vertex) print('Vertex:' + vertex) vertex_iterator = graph.vertex_object[destination] bfs_stack = [] while vertex_iterator != graph.vertex_object[source]: if not vertex_iterator.prev_search: print('No path between source and destination') return bfs_stack.append(vertex_iterator.name) vertex_iterator = graph.vertex_object[vertex_iterator.prev_search] bfs_stack.append(source) print([x for x in reversed(bfs_stack)])
def simulation(numSeconds, pagesPerMinute): labprinter = Printer(pagesPerMinute) printQueue = Queue() waitingtimes = [] for currentSecond in range(numSeconds): if newPrintTask(): task = Task(currentSecond) printQueue.enqueue(task) if (not labprinter.busy()) and (not printQueue.empty()): nexttask = printQueue.dequeue() waitingtimes.append(nexttask.waitTime(currentSecond)) labprinter.startNext(nexttask) labprinter.tick() averageWait = sum(waitingtimes) / len(waitingtimes) print("Average Wait %6.2f secs %3d tasks remaining." % (averageWait, printQueue.size()))
def bfs(gui, one_step=False): starting_pos = gui.grid.head.get_node() fringe = Queue() # Fringe holds a list of tuples: (node position, move to get prev to current, cost) fringe.enqueue([(starting_pos, None, 0)]) path = [] visited = [starting_pos] while not fringe.is_empty(): # Get the next one to be popped off the stack to search it's neighbor nodes (successors) path = fringe.dequeue() if gui.grid.grid[path[-1][0][0]][path[-1][0][1]] == 3: break for neighbor in get_neighbors(gui, path[-1][0][0], path[-1][0][1]): if neighbor[0] not in visited: updated_path = copy.copy(path) updated_path.append(neighbor) fringe.enqueue(updated_path) if not gui.grid.grid[neighbor[0][0]][neighbor[0][1]] == 3: visited.append(neighbor[0]) if not fringe.is_empty(): move_set = [] while path: temp = path.pop(0) if temp[1] is not None: move_set.append(temp[1]) if not one_step: return move_set else: return [move_set[0]] else: no_bfs_move = go_furthest(gui) if no_bfs_move: return no_bfs_move else: no_moves_at_all = go_down() return no_moves_at_all
def test_enqueue(self): q = Queue() q.enqueue('A') assert q.front() == 'A' assert q.length() == 1 q.enqueue('B') assert q.front() == 'A' assert q.length() == 2 q.enqueue('C') assert q.front() == 'A' assert q.length() == 3 assert q.is_empty() is False
def trasverse_levelorder(self): levels = [[]] q = Queue() q.enqueue({"node": self.root, "level": 0}) while not q.queue_empty(): x = q.dequeue() # Save node to appropriate level. if x["level"] == len(levels): # Create new level. levels.append([x["node"].key]) else: # Save to existing level. levels[x["level"]].append(x["node"].key) # Proceed with the queue. if x["node"].left is not None: q.enqueue({"node": x["node"].left, "level": x["level"] + 1}) if x["node"].right is not None: q.enqueue({"node": x["node"].right, "level": x["level"] + 1}) return levels
class Grid(): # initialize the Grid, Default height and length 20x20 def __init__(self, height=20, length=20): self.height = height self.length = length self.grid = [] self.grew = False self.head = Snake_Node(0, 0) self.temp_head = Snake_Node(0, 0) # Re-used snake node to keep location of food on grid self.food_location = Snake_Node(0, 0) # The tail is a queue of snake nodes self.tail = Queue() self.isdead = False self.create_grid() self.snake_head_start_location() self.spawn_food() # Set every node in the grid to zero def reset_grid(self): for row in range(self.height): for col in range(self.length): self.grid[row][col] = 0 # Create a grid that is initialized to zero def create_grid(self): for row in range(self.height): self.grid.append([]) for col in range(self.length): self.grid[row].append(0) # This is to update any given value on the grid. # 0 for empty # 1 for snake head # 2 for snake body # 3 for food def update_grid(self, row, col, value): self.grid[row][col] = value # This spawns food at a random location on the map not occupeied by other things def spawn_food(self): row = random.randint(0, self.height-1) col = random.randint(0, self.length-1) while self.grid[row][col] != 0: row = random.randint(0, self.height-1) col = random.randint(0, self.length-1) self.food_location = Snake_Node(row, col) self.update_grid(row, col, 3) # This spawns the snake head in the center of the grid def snake_head_start_location(self): start_row = random.randint(0, self.height-1) start_col = random.randint(0, self.length-1) self.head = Snake_Node(start_row, start_col) self.update_grid(start_row, start_col, 1) # The tail moves, It sheds its old tail end and has a new tail start def update_tail(self, head): self.tail.enqueue(head) self.update_grid(head.row, head.col, 2) # Snakes shed skin so this is the tail that it 'shed' as it moved shed = self.tail.dequeue() self.update_grid(shed.row, shed.col, 0) # The tail grows, It doesnt shed its old tail end and has a new tail start def grow(self, head): self.tail.enqueue(head) self.update_grid(head.row, head.col, 2) # The action of eating food makes the snake grow in size by one. def eat_food(self): self.grow(self.temp_head) # The action of slithering down the grid, not losing / gaining any length def move_tail(self): self.update_tail(self.temp_head) # Move the head to a new position (the rest of the snake will follow) def move_head(self, row_move, col_move): new_node = Snake_Node(self.head.row + row_move, self.head.col + col_move) self.head = new_node self.update_grid(new_node.row, new_node.col, 1) # This will move the snake. Only one move per 'turn', either row or col move, not both. def snake_move(self, row_move, col_move): # Checks to see if a move is legal, An illegal move does result in death! if self.snake_check_move(row_move, col_move): # Move is good, just moving through the grid if self.grid[self.head.row + row_move][self.head.col + col_move] == 0: self.grew = False self.temp_head = self.head self.move_head(row_move, col_move) self.move_tail() # Move is impossible, There is an error elif self.grid[self.head.row + row_move][self.head.col + col_move] == 1: self.grew = False # Move ends in death, Head hit the body elif self.grid[self.head.row + row_move][self.head.col + col_move] == 2: self.grew = False if self.grid[self.head.row + row_move][self.head.col + col_move] == 2: self.dead() # Move makes the snake grow. We just ate food!! elif self.grid[self.head.row + row_move][self.head.col + col_move] == 3: self.grew = True self.temp_head = self.head self.move_head(row_move, col_move) self.eat_food() self.spawn_food() # The snake hit a wall else: self.grew = False self.dead() # Check to see if a move with cross the boundry. If bad move then DEAD # Returns true if legal move, Returns false if illegal move def snake_check_move(self, row_move, col_move): legal = True if row_move == 0 and col_move == 0: legal = False #print("From Grid: don't stay still") return legal # Top Row if self.head.row == 0: # Top Left Corner (No Moving left or up) if self.head.col == 0: if row_move == -1 or col_move == -1: #print("From Grid: don't cross top left") legal = False # Top Right Corner (No Moving Right or Up) elif self.head.col == self.length - 1: if row_move == -1 or col_move == 1: #print("From Grid: don't cross top right") legal = False # Top Row - no Corners (No Moving Up) else: if row_move == -1: #print("From Grid: don't cross top") legal = False # Bottom Row elif self.head.row == self.height - 1: # Bottom left corner (No moving down or left) if self.head.col == 0: if row_move == 1 or col_move == -1: #print("From Grid: don't cross bottom left") legal = False # Bottom Right Corner (No movin Down or Right) elif self.head.col == self.length - 1: if row_move == 1 or col_move == 1: #print("From Grid: don't cross bottom right") legal = False # Bottom Row - No Corners (No moving down) else: if row_move == 1: #print("From Grid: don't cross bottom") legal = False # Very Left - No corners (No moving left) elif self.head.col == 0: if col_move == -1: #print("From Grid: don't cross left") legal = False # Very Right - No Corners (No moving Right) elif self.head.col == self.length - 1: if col_move == 1: #print("From Grid: don't cross right") legal = False # If not_if_hitting_body returns false, then the snake WILL die , so it is not a legal move. if legal and not self.not_if_hitting_body(row_move, col_move): #print("From Grid: don't hit body") legal = False return legal # This will return TRUE if the snake hits a wall or itself. DEAD BOI def dead(self): self.isdead = True # This will return False if next move WILL hit self, and True if it WILL NOT def not_if_hitting_body(self, row_move, col_move): head_x, head_y = self.head.get_node() if self.grid[head_x + row_move][head_y + col_move] == 2: return False else: return True
def random_queue(length=20): queue = Queue() for _ in range(length): queue.enqueue(randint(1, 10)) return queue
def test_is_empty(): queue = Queue() assert queue.is_empty() is True queue.enqueue(1) assert queue.is_empty() is False
'''------------Second Part--------------''' # user enters str values into stack line = input("Enter a string,'end' to stop: ") while (line != 'end'): stack.push(line) line = input("Enter a string,'end' to stop:") # user typed str values are removed from stack and printed while not(stack.is_empty()): print(stack.pop()) '''-------------Third Part----------------''' # same user interaction as before, except use a Queue instead of Stack queue = Queue() line = int(input("Enter a string,'end' to stop: ")) while (line != 'end'): queue.enqueue(line) #convert line to an int unless it is 'end' line = (input("Enter a string,'end' to stop:")) if line != 'end': line = int(line) product = 1 while not(queue.is_empty()): product *= queue.dequeue() print(product)
def test_po_dodaniu_elementu_kolejka_nie_jest_pusta(self): q = Queue() q.enqueue(123) self.assertFalse(q.is_empty())
def test_peek(): queue = Queue() queue.enqueue(1) assert queue.peek() == 1
def test_po_dodaniu_i_usunieciu_elementu_kolejka_jest_pusta(self): q = Queue() q.enqueue(123) q.dequeue() self.assertTrue(q.is_empty())
def test_po_dodaniu2_i_usunieciu1_elementu_kolejka_nie_jest_pusta(self): q = Queue() q.enqueue(123) q.enqueue(456) q.dequeue() self.assertFalse(q.is_empty())
import sys sys.path.append('..') from my_queue import Queue # Setup q = Queue(1) q.enqueue(3) # Test peek # Should be 1 assert (q.peek() == 1), "Failed in q.peek()" # Test dequeue # Should be 1 assert (q.dequeue() == 1), "Failed in q.dequeue()" # Test enqueue q.enqueue(4) # Should be 3 assert (q.dequeue() == 3), "Failed in q.dequeue()" # Should be 4 assert (q.dequeue() == 4), "Failed in q.dequeue()" q.enqueue(5) # Should be 5 assert (q.peek() == 5), "Failed in q.peek()" print ("ALL TEST PASSED")
def test_pierwszy_wchodzi_pierwszy_wychodzi(self): q = Queue() q.enqueue(123) q.enqueue(456) self.assertEqual(q.dequeue(), 123)
def test_drugi_wchodzi_drugi_wychodzi(self): q = Queue() q.enqueue(123) q.enqueue(456) q.dequeue() self.assertEqual(q.dequeue(), 456)