def a_star_search(problem, fringe): # If there is no node on fringe, make one if len(fringe.queue) <= 0: initial_node = Node(problem) fringe.insert(initial_node) # If nodes don't have path cost for A* Search, give them one for node in fringe.queue: if node.a_star_cost == None: node.a_star_cost = a_star_evaluator(node) # Form a temporary priority queue a_star_fringe = Queue() a_star_fringe.insert_all(fringe.queue) # Sort them according to lowest path cost bubble_sort(a_star_fringe, False) # Iterate over the sorted nodes, to check visually for nodes in a_star_fringe.queue: print('Node: ' + str(nodes.a_star_cost) + ' Depth: ' + str(nodes.depth) + ' Action: ' + str(nodes.action)) # Now do the good stuff # Get the first node in A* fringe and then pop it on the main fringe greed_node = a_star_fringe.pop() node = fringe.pop_specific(greed_node) # If the node is the goal, return it as goal; otherwise expand it if goal_test(node.state) == True: return True, solution(node), node else: if node.state.connor.death == False: fringe.insert_all(expand(node)) return False, fringe, node
def best_fs(problem, fringe): # If there is no node on fringe, make one if len(fringe.queue) <= 0: initial_node = Node(problem) fringe.insert(initial_node) # If nodes don't have path cost for Greedy BFS, give them one for node in fringe.queue: if node.greed_cost == None: node.greed_cost = best_fs_evaluator(node) # Form a temporary priority queue best_fs_fringe = Queue() best_fs_fringe.insert_all(fringe.queue) # Sort them according to lowest path cost bubble_sort(best_fs_fringe) # Now do the good stuff # Get the first node in Greedy BFS fringe and then pop it on the main fringe greed_node = best_fs_fringe.pop() node = fringe.pop_specific(greed_node) # If the node is the goal, return it as goal; otherwise expand it if goal_test(node.state) == True: return True, solution(node), node else: if node.state.connor.death == False: fringe.insert_all(expand(node)) return False, fringe, node
class EventsHub: """Implements an event aggregator to gather events from both interfaces as well as the application itself. Similar to an Observer pattern. Warning: Events need to be processed regularly by calling `.handle_events()` to avoid overflowing the event queue. Events types: - pygame events (mouse / key press / quit) - tkinter events (mouse / key press / quit) - all buttons - application events, like "AnimationFinished" event """ def __init__(self): self._events = Queue() self._callbacks = {} def raise_event(self, event): self._events.put(event) def add_callback(self, event_name, callback): self._callbacks.setdefault(event_name, []).append(callback) def handle_events(self): while not self._events.empty(): event = self._events.pop() if event.type in [Event.QUIT, Event.NEWFRAME]: # print("Handling", event, self._callbacks.get(event.type, [])) pass for callback in self._callbacks.get(event.type, []): callback(event)
def __bfs(graph, beg_id, end_id, shortest_path=True): first = graph.vtx_map[beg_id] queue = Queue([first]) visited = set([first.id]) nearest_prevs_hmap = {} found = False while len(queue) != 0: # explore: (prev node not always unique.) # Goes through all nodes prev_node = queue.dequeue() neighbors_ids_wts = prev_node.adj_list for cur_id, _ in neighbors_ids_wts: if cur_id not in visited: # visit: (cur_node always unique) # update `queue` and `visited` queue.enqueue(graph.vtx_map[cur_id]) visited.add(cur_id) # action - populate hmap # can break if end_id is found cz # we add all nearest prevs until `cur_id` in lookup table nearest_prevs_hmap[cur_id] = prev_node.id if cur_id == end_id: found = True break if found is True: break # at end of bfs traversal/search return nearest_prevs_hmap
def __init__(self, G): self.marked = [False for _ in range(G.V)] self.pre = Queue() # push v to queue before recursion self.post = Queue() # ... after recursion self.reverse_post = Stack() # push v to stack after recursion for w in range(G.V): if not self.marked[w]: self.dfs(G, w)
def __init__(self, name): self.name = name self.centerList = Queue.Queue(queue_size, (0, 0)) self.size = 0 self._foundQueue = Queue.Queue(queue_size, 0) self.found = False self.lastFoundFrame = 0 self.logging = True self.idCentroid = 0 #persona che è stata vista più di 4 volte e che quindi può entrare self.possibleEntering = False
def test_queue(): q = Queue() q.enqueue(3) assert_equal(1, q.size()) assert_equal(3, q.dequeue()) q.enqueue(2) q.enqueue(1) assert_equal([2, 1], list(q)) assert_equal(2, q.dequeue())
def main_loop(): hardware = None try: print('Setting up hardware...') hardware = Hardware() # Set up job queue queue = Queue(hardware) print('Connecting to IotHub...') IotHub(hardware=hardware, queue=queue) print('Setting up background jobs...') def sensor_reading(): return queue.append( "periodic_reading", {"methods": ['read_humidity', 'read_light', 'read_pressure']}) def soil_moisture_reading(): return queue.append("periodic_reading", { "methods": ['read_mcp3008_soil_moisture', 'read_water_level'] }) # Read humidity, light, pressure and temperature frequently schedule.every(PERIODIC_READING_INTERVAL).seconds.do(sensor_reading) # Read soil moisture and water level twice a day schedule.every().day.at("06:00").do( soil_moisture_reading) # 08:00 Swedish summer time schedule.every().day.at("18:00").do( soil_moisture_reading) # 20:00 Swedish summer time print('App ready!') while True: # Add scheduled jobs to queue schedule.run_pending() # Pop queue queue.work() time.sleep(1) except KeyboardInterrupt: print('Process ended by user.') except Exception as inst: print('Unexpected error!') print(type(inst)) print(inst.args) print(inst) finally: shutdown_gracefully(hardware)
def bfs(self, starting_vertex, destination_vertex): """ Return a list containing the shortest path from starting_vertex to destination_vertex in breath-first order. """ # make a queye q = Queue() # make a set to track the nodes visited = set() path = [starting_vertex] # enqueue the starting node q.enqueue(path) # while the queue isn't empty while q.size() > 0: ## dequee the node at the front of the line current_path = q.dequeue() current_node = current_path[-1] ### if this node is out targte node if current_node == destination_vertex: #### return it!! return True return current_path ### if not visted if current_node not in visited: #### mark as visited visited.add(current_node) #### get neigghbots neighbors = self.vertices[current_node].keys() # for each neibor for neighbor in neighbors: path = list(current_node) # add to queue path.append(neighbor) q.enqueue(path)
def bfs(graph, starting_vertex, destination_vertex): """ Return a list containing the shortest path from starting_vertex to destination_vertex in breath-first order. """ # Create a q and enqueue starting vertex qq = Queue() qq.enqueue([starting_vertex]) # Create a set of traversed vertices visited = set() # visited = [] # While queue is not empty: while qq.size() > 0: # dequeue/pop the first vertex path = qq.dequeue() # if not visited if path[-1] not in visited: # DO THE THING!!!!!!! print(path[-1]) # mark as visited visited.add(path[-1]) print(path) # visited.append(path[-1]) # enqueue all neightbors if path[-1] == destination_vertex: return path for next_vert in graph[path[-1]].keys(): new_path = list(path) # print(new_path) new_path.append(next_vert) qq.enqueue(new_path) # print(visited) pass # TODO
def bfs(visited_rooms): visited = set() my_queue = Queue() room = player.current_room # add room id my_queue.enqueue([room.id]) while my_queue.size() > 0: path = my_queue.dequeue() # the last node end = path[-1] if end not in visited: visited.add(end) # checks if last room has been visited for exit_direction in visited_rooms[end]: # if no exit exists if (visited_rooms[end][exit_direction] == '?'): return path # if not visited elif (visited_rooms[end][exit_direction] not in visited): # create/ add a new path new_path = path + [visited_rooms[end][exit_direction]] # add the new path my_queue.enqueue(new_path) return path
def find_room(self): # implement bfs to find path to nearest unseen room # def bfs(self, starting_vertex, destination_vertex): # """ # Return a list containing the shortest path from # starting_vertex to destination_vertex in # breath-first order. # """ # initialize queue with starting vertex queue = Queue() queue.enqueue((self.current_room, [])) # set to keep track of vertexes already seen visited = set() # while queue is not empty while queue.size() > 0: # get path and vertex room, path = queue.dequeue() # if room has not been seen, return path if room.id not in self.seen: return path # else, add vertex to visited elif room.id not in visited: visited.add(room.id) # and add paths to the queue for each edge for exit in room.get_exits(): path_copy = path.copy() path_copy.append(exit) queue.enqueue((room.get_room_in_direction(exit), path_copy)) print('Room not found')
def find_shortest_path(graph, starting_room): qq = Queue() visited = set() qq.enqueue([starting_room]) while qq.size() > 0: path = qq.dequeue() move = path[-1] room = path[-1].origin if move.dir: room = graph[room][move.dir] if room not in visited: visited.add(room) for exit in graph[room]: # Target(?) found! if graph[room][exit] == '?': new_move = Move(room, exit) return path[1:], new_move # If target not found make a new move and append to queue elif exit != '?' and graph[room][exit] not in visited: new_path = list(path) new_move = Move(room, exit) new_path.append(new_move) qq.enqueue(new_path) return None, None
def linearize_level_ordered(self, level=1): graph_str = '' bfs_queue = Queue() cur_level_count = 0 visited = {key: False for key in self.graph} for root in self.roots: bfs_queue.enqueue(root) cur_level_count += 1 while not bfs_queue.isEmpty() and level > 0: next_level_count = 0 while cur_level_count > 0: cur_item = bfs_queue.dequeue() if not visited[cur_item]: visited[cur_item] = True if global_info.node_labels[cur_item].find( 'name_' ) != -1 or global_info.node_labels[cur_item].find( 'date-entity' ) != -1: # skip name and date entity as global concepts cur_level_count -= 1 continue graph_str += global_info.node_labels[cur_item] + _SPACE for neighbour in self.graph[cur_item].adjacency_list: next_level_count += 1 bfs_queue.enqueue(neighbour[0]) cur_level_count -= 1 cur_level_count = next_level_count level -= 1 return graph_str
def bfs(start_room, map): # Create an empty Queue and enqueue path to starting_vertex q = Queue() q.enqueue([start_room]) # Create empty set to store visted nodes visited = set() # While queue is not empty: while q.size() > 0: # Dequeue the first path path = q.dequeue() # get vertex from end of path node = path[-1] # if the vertex has not been visited if node not in visited: # mark it visted visited.add(node) # Check if it contains a "?" if "?" in map[node].values(): return path # then add a path to all adjacent vertices to back of queue for neighbor in map[node].values(): # copy path copy_path = path.copy() # append next vert to back of copy copy_path.append(neighbor) # enqueue copy q.enqueue(copy_path) return None
def bft(self, starting_vertex: T) -> None: """ Print each vertex in breadth-first order beginning from starting_vertex. """ # keep track of visited vertices visited = set() # create a queue class queue = Queue() # enqueue the starting vertex queue.enqueue(starting_vertex) # while queue is not empty while queue.size(): # dequeue the queue current_vertex = queue.dequeue() # if current vertex has not been visited if current_vertex not in visited: # add ti to visited visited.add(current_vertex) # print the current vertex print(current_vertex) # for every neighbors of current_vertex for vertex in self.vertices[current_vertex]: # add it to the queue queue.enqueue(vertex)
def search(grid,init,goal,cost): # ---------------------------------------- # insert code here # ---------------------------------------- Nr=len(grid) Nc=len(grid[0]) def childNode(grid, loc, delta, delta_name): child=[] for i in range(len(delta)): move=delta[i] newloc=[loc[0]+move[0], loc[1]+move[1]] if loc[0]+move[0]>=0 and loc[0]+move[0]<Nr \ and loc[1]+move[1]>=0 and loc[1]+move[1]<Nc \ and grid[newloc[0]][newloc[1]] ==0: child.append([newloc,delta_name[i]]) return child visited=[] frontier=Queue() frontier.push([init,0]) while not frontier.isEmpty(): loc, rlen=frontier.pop() if not loc in visited: visited.append(loc) if loc==goal: return [rlen, loc[0], loc[1]] for nextloc, move_name in childNode(grid, loc, delta, delta_name): if not nextloc in visited: frontier.push([nextloc, rlen+cost]) return 'fail'
def get_directions(starting_room, destination_room, all_rooms): # Create an empty queue queue = Queue() # Add a path for starting_room_id to the queue # Add a second option that recalls to room zero first # paths will contain tuple of (direction, room_id) queue.enqueue([(None, starting_room)]) # queue.enqueue([(None, starting_room), (None, 0)]) # Create an empty set to store visited rooms visited = set() while queue.size() > 0: # Dequeue the first path path = queue.dequeue() # Grab the last room from the path room = path[-1][1] # If room is the desination, return the path if room == destination_room: return path[1:] # If it has not been visited... if room not in visited: # Mark it as visited visited.add(room) # Then add a path all neighbors to the back of the queue current_room = all_rooms[str(room)] adjacent_rooms = [] for e in current_room['exits']: adjacent_rooms.append((e, current_room['exits'][e])) for next_room in adjacent_rooms: queue.enqueue(path + [next_room])
def bfs(self, starting_vertex, destination_vertex): """ Return a list containing the shortest path from starting_vertex to destination_vertex in breath-first order. """ # make a queue queue = Queue() # make a visited set visited = set() # enqueue the PATH to that node queue.enqueue([starting_vertex]) # While queue isn't empty while queue.size(): # dequeue the PATH path = queue.dequeue() # the last thing in the path is our current item node = path[-1] # if node is not visited: if node not in visited: # CHECK if it's the target if node == destination_vertex: # if so, return the path return path visited.add(node) # for each of the node's neighbor's for neighbor in self.vertices[node]: #copy the path PATH_COPY = path.copy() # add neighbor to the path PATH_COPY.append(neighbor) # enqueue the PATH_COPY queue.enqueue(PATH_COPY) return None
def __init__(self, user_accounts): """Initialization Args: user_accounts (list): user account details from bank """ self.user_accounts = user_accounts self.options = None self.option_states = [] self.q = Queue() self.q.enqueue(self.init) self.curr_acc = None
def __init__(self, parent=None): tk.Frame.__init__(self, parent) self.grid(column=0, row=0) self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self.parent = parent self.test_problem = State() self.test_fringe = Queue() self.problem = State() self.solution = tree_search(self.test_problem, self.test_fringe) self.solution_stage = 0 self.connor_hp = tk.IntVar() self.arnold_hp = tk.IntVar() self.connor_defense = tk.StringVar() self.arnold_defense = tk.StringVar() self.update() name_column = 1 data_column = 2 self.ui_label(1, name_column, 'Connor') self.ui_label(4, name_column, 'Arnold') self.ui_label(2, name_column, 'Defense') self.ui_label(5, name_column, 'Defense') self.ui_label(1, data_column, self.connor_hp, True) self.ui_label(4, data_column, self.arnold_hp, True) self.ui_label(2, data_column, self.connor_defense, True) self.ui_label(5, data_column, self.arnold_defense, True) self.ui_btn(6, data_column, 'Next', self.resolve)
def __init__(self, event_hub: EventsHub): self.state = RubiksCube() self._generate_cubes(self.state.cubes) self._animation: Queue = Queue() # Stores animations to move faces self.event_hub = event_hub self._add_listeners()
class Account(object): account = dict() fax = 0 kline = Queue.Queue() MIN_DATA_COUNT = 26 * 3 + 1 MAX_DATE = None def __init__(self): print() #获取K线数据 def getKlines(self): raise NotImplementedError() #获取账户余额 def getAccountBalance(self): raise NotImplementedError() #买币 def buy(self, ratio, kline): raise NotImplementedError() def sell(self, ratio, kline): raise NotImplementedError() def initWithKeySecret(self, key, secret): raise NotImplementedError()
def solve(board, robots, dest, dest_color, num_sols=3, max_depth=20): """ Robots denotes the position and orientation (above or below a diag) of the robots. The robot of color DEST_COLOR must get to the square given by DEST (an (x, y) tuple). A list of Solution objects are returned, NUM_SOLS many of them (the best, second best, etc.) If we haven't found a solution less than MAX_DEPTH, give up """ assert len(robots) == 4, "there must be 4 robots" assert dest_color in ["yellow", "red", "green", "blue"] assert num_sols >= 0 and max_depth >= 0, "Cannot have a negative number of solutions or max depth" print "Trying to move", dest_color, "robot to", dest solutions = [] if num_sols == 0: return solutions # initialize the BFS fringe initial_sol = Solution(robots) bfs_fringe = Queue() bfs_fringe.enqueue(initial_sol) # in loop: dequeue, check if solution, add all next positions to queue curr_depth = 0 num_sols_at_depth = 0 while True: assert not bfs_fringe.empty(), "BFS fringe is empty" # dequeue the Solution at the front of the stack curr_sol = bfs_fringe.dequeue() # if it is a valid solution for the board, add it to the list of solutions to return if board.isSolution(curr_sol, dest, dest_color): solutions.append(curr_sol) if len(solutions) == num_sols: return solutions if curr_sol.depth > curr_depth: print "Examined", num_sols_at_depth, "solutions at depth", curr_depth curr_depth = curr_sol.depth num_sols_at_depth = 0 # check that the depth of this solution does not exceed max depth num_sols_at_depth += 1 if num_sols_at_depth % 100 == 0: print "Examined", num_sols_at_depth, "solutions at depth", curr_depth if curr_sol.depth > max_depth: break # for each of the possible robot moves, make the move, grab the new Solution and enqueue it next_moves = board.allNextMoves(curr_sol) for next_move in next_moves: bfs_fringe.enqueue(next_move) return solutions
def BFS(self, s): ''' Breadth first search algorithm (BFS) Input: s - start vertex Output: visited (set) - the set of accessible vertices from s prev (dictionary) - each key has as value the vertex that is previous to the key in the BFS path dist (dictionary) - each key represent a vertex and has as value the length of the shortest path from s to it ''' visited = set() # set q = Queue() # queue prev = {} # dictionary dist = {} # dictionary prev[s] = None dist[s] = 0 q.enqueue(s) while len(q) > 0: x = q.dequeue() # get the next element from the queue for y in self.__dg.iterateOut(x): if y not in visited: visited.add(y) q.enqueue(y) prev[y] = x dist[y] = dist[x] + 1 return visited, prev, dist
def search(grid, init, goal, cost): # ---------------------------------------- # insert code here # ---------------------------------------- Nr = len(grid) Nc = len(grid[0]) expand = [[-1 for j in range(Nc)] for i in range(Nr)] policy = [[' ' for j in range(Nc)] for i in range(Nr)] path = [[' ' for j in range(Nc)] for i in range(Nr)] count = 0 def childNode(grid, loc, delta, delta_name): child = [] for i in range(len(delta)): move = delta[i] newloc = [loc[0] + move[0], loc[1] + move[1]] if loc[0]+move[0]>=0 and loc[0]+move[0]<Nr \ and loc[1]+move[1]>=0 and loc[1]+move[1]<Nc \ and grid[newloc[0]][newloc[1]] ==0: child.append([newloc, delta_name[i]]) return child visited = [] frontier = Queue() frontier.push([init, ' ', 0]) while not frontier.isEmpty(): loc, mov, rlen = frontier.pop() if not loc in visited: visited.append(loc) policy[loc[0]][loc[1]] = mov if loc == goal: path[goal[0]][goal[1]] = '*' while loc != init: x, y = loc if policy[x][y] == 'v': loc = [x - 1, y] path[loc[0]][loc[1]] = 'v' elif policy[x][y] == '^': loc = [x + 1, y] path[loc[0]][loc[1]] = '^' elif policy[x][y] == '>': loc = [x, y - 1] path[loc[0]][loc[1]] = '>' elif policy[x][y] == '<': loc = [x, y + 1] path[loc[0]][loc[1]] = '<' return path for nextloc, move_name in childNode(grid, loc, delta, delta_name): if not nextloc in visited: frontier.push([nextloc, move_name, rlen + cost]) return 'fail'
class DepthFirstOrder: def __init__(self, G): self.marked = [False for _ in range(G.V)] self.pre = Queue() # push v to queue before recursion self.post = Queue() # ... after recursion self.reverse_post = Stack() # push v to stack after recursion for w in range(G.V): if not self.marked[w]: self.dfs(G, w) def dfs(self, G, v): self.pre.enqueue(v) self.marked[v] = True for w in G.adj[v]: if not self.marked[w]: self.dfs(G, w) self.post.enqueue(v) self.reverse_post.push(v)
def build_path(self, G, s): self.marked[s] = True queue = Queue() queue.enqueue(s) while not queue.is_empty(): v = queue.dequeue() for w in G.adj[v]: if not self.marked[w]: self.edge_to[w] = v self.marked[w] = True queue.enqueue(w)
def evaluate(self, vars): stack = Stack() queue = Queue() for elem in self._rpn: factory = OperatorFactory() operator = factory.newOperator(elem, stack, vars) if self.verbose == True: print elem, operator.evaluate() stack.push(operator.evaluate()) if self.verbose == True: print stack.s() return stack.popAll()
def test_pop_2(self): q = Queue() q.put(2) q.put(1) self.assertEqual(q.pop(), 2) self.assertEqual(q.pop(), 1) self.assertTrue(q.empty())
def convert(self, verbose): self.verbose = verbose operators = "^*+-\/" # operands = string.ascii_lowercase + string.digits output = Queue() stack = Stack() for token in self.infix: operands = re.match("^[a-z]$|^\d+\.\d+$|^\d+$", token) operators = re.match("^[+-\/*^]$", token) # if token is a number or variable add it to putput if operands: output.push(token) if self.verbose == True: print "1 token = %s, output = %s" % (token, output.list[::-1]) # if the token is variable add it mapVariable dictionary if token in string.ascii_lowercase: self.mapVariables[token] = "" # if token is an operator elif operators: # while there is another operator on the stack while not stack.isEmpty(): # if operator is lef-associative and its precedence is less than or equal to that on stack, or operator has precedence less than that on stack (is not left-associative) if stack.lastOnStack() != "(" and ( ( self.precedence[token][0] <= self.precedence[stack.lastOnStack()][0] and self.precedence[token][1] == "L" ) or self.precedence[token][0] < self.precedence[stack.lastOnStack()][0] ): # push operator to output from stack output.push(stack.pop()) if self.verbose == True: print "2 token = %s, output = %s" % (token, output.list[::-1]) else: break # push operator to stack stack.push(token) if self.verbose == True: print "3 token = %s, stack = %s" % (token, stack.list[::-1]) # if token is left parenthesis push it to stack elif token == "(": stack.push(token) if self.verbose == True: print "4 token = %s, stack = %s" % (token, stack.list[::-1]) # if token is right parenthesis elif token == ")": # until token at the top of stack is not left parethesis while stack.lastOnStack() != "(": # push from stack to output output.push(stack.pop()) if self.verbose == True: print "5 token = %s, output = %s" % (token, output.list[::-1]) # and pop left parethesis from stack but not to output stack.pop() if self.verbose == True: print "Left on stack " + str(stack.list[::-1]) print "Output " + str(output.list) self._rpn = output.list[::-1] while len(stack.list) > 0: self._rpn.append(stack.pop()) if self.verbose == True: print "RPN value = " + str(self._rpn) return self._rpn
import re from utils import Stack from utils import Queue def recu(s, out, stk): print s for token in s: print token dig = re.match('\d+', token) oper = re.match('[\+\-\/\*]', token) if token == '(': a = s[s.index(token)+1:s.index(')')] print "obciachane ", a del s[s.index(')')] recu(a, out, stk) elif dig: out.push(token) elif oper: stk.push(token) output = Queue() stack = Stack() s1 = '(2+3)*5' s2 = re.split('\s*([+\-*/()]|\d+\.\d+|\d+)\s*', s1) recu(s2, output, stack) print output.popAll(), stack.popAll()