def __init__(self, m: maze.Maze, start: tuple = None, goal: tuple = None, single_mode: bool = False): self.maze = m # back is the goal self.single_mode = single_mode if goal is None: self.back = (self.maze.getDim() - 1, self.maze.getDim() - 1) else: self.back = goal if start is None: self.front = (0, 0) else: self.front = start # define all of the front self.front_visited = set() self.front_previous = dict() self.front_fringe = queue() self.front_fringe.append(self.front) # define all of the back self.back_visited = set() self.back_previous = dict() self.back_fringe = queue() self.back_fringe.append(self.back)
def solve_bfs(start_id: str, end_id: str, nodes, edges): solution_t_start = perf_counter() solution = [] # Initialize data structures fringe = queue() # Queue to hold nodes to check since it's FIFO visited = { } # Dict/hash-map for nodes already checked: key = node, value = parent # Add initial node to collections fringe.append((0, start_id)) visited[start_id] = None # Start node has no parents while len(fringe) > 0: current_distance, current_id = fringe.popleft() current_y, current_x = nodes[current_id] if current_id == end_id: this_id = current_id path = queue() while not this_id == start_id: path.appendleft(this_id) this_id = visited[this_id] return current_distance, solution, perf_counter( ) - solution_t_start, associations_to_path(visited, end_id, nodes) for child_id, c_to_child_distance in edges[current_id]: if child_id not in visited: fringe.append( (current_distance + c_to_child_distance, child_id)) visited[child_id] = current_id child_y, child_x = nodes[child_id] solution.append(((current_y, current_x), (child_y, child_x))) return None
def __init__(self, debug=False, step=False): """Initialize a machine control. It setups up a machine list, which in this implementation is a queue. Reaction maps are created as dictionaries, and the event buss is another queue. The `ctx` variable is not yet set. This happens when the simulator is started. Keyword Args: debug: opens a window for each state machine showing state \ and event information if True (default True) step: allows one to cycle stepwise (default False) """ self.machines = queue() self.event_reactions = {} self.machine_reactions = {} self.event_buss = queue() self.ctx = None self.debug = debug self.react_event = None self.step = step self.event_n = 0 if debug: self.debug_windows = {}
def __init__(self, players=[], price=100, pendingbuys=queue(), pendingsells=queue()): self.price = price self.players = players self.pendingbuys = pendingbuys self.pendingsells = pendingsells
def associations_to_path(associations: dict, goal_id: str, nodes) -> list: this_id = goal_id path = queue() while not this_id is None: path.appendleft(nodes[this_id]) this_id = associations[this_id] return list(path)
def solution(begin, target, words): if target not in words: return 0 q, d = queue(), dict() q.append((begin, 0)) # 단어 비교 d[begin] = set(filter(lambda x: transistable(x, begin), words)) # 하나씩 차이나는 단어 체크 for w in words: d[w] = set(filter(lambda x: transistable(x, w), words)) while q: cur, level = q.popleft() #단어 cur, 변환 과정의 횟수 level # 전부 탐색해도 목표 단어를 만들지 못함 or 단어의 소비가 끝남에도 목표 단어 못 만듦 if level > len(words): return 0 # 단어를 채운 큐를 목표 단어를 만들 때까지 탐색 for w in d[cur]: if w == target: return level + 1 else: q.append((w, level + 1))
def findDistance(matrix): output = [[-1 for i in range(N)] for i in range(M)] q = queue() for i in range(M): for j in range(N): output[i][j] = -1 if matrix[i][j] == 'G': pos = [i, j, 0] q.appendleft(pos) output[i][j] = 0 #elif matrix[i][j] == 'W': # output[i][j] = -1 while (len(q) > 0): curr = q.pop() x, y, dist = curr[0], curr[1], curr[2] for i in range(4): if isValid(x + row[i], y + col[i]) and isSafe( x + row[i], y + col[i], matrix, output): output[x + row[i]][y + col[i]] = dist + 1 pos = [x + row[i], y + col[i], dist + 1] q.appendleft(pos) for i in range(M): for j in range(N): if output[i][j] > 0: print(output[i][j], end=" ") else: print(output[i][j], end=" ") print()
def levelOrder(root): if (root == None): return # Create an empty queue for # level order tarversal q = queue() # To store front element of # queue. #node *curr # Enqueue Root and None node. q.append(root) q.append(None) while (len(q) > 1): curr = q.popleft() #q.pop() # Condition to check occurrence of next level. if (curr == None): q.append(None) print() else: # Pushing left child of current node. if (curr.left): q.append(curr.left) # pushing right child of current node. if (curr.right): q.append(curr.right) print(len(curr.data), end = " ")
def levelOrderTraversal(rootNode): #Time - O(N) Space-O(N) if not rootNode: return # Create an empty queue for # level order traversal q = queue() # To store front element of # queue. #node *curr # Enqueue Root and None node. q.append(rootNode) q.append(None) while (len(q) > 1): curr = q.popleft() # Condition to check # occurrence of next # level. if (curr == None): q.append(None) print() else: # Pushing left child of # current node. if (curr.leftChild): q.append(curr.leftChild) # Pushing right child of # current node. if (curr.rightChild): q.append(curr.rightChild) print(curr.data, end=" ")
def find_valid_adjacent_nodes(self, matrix_node: tuple, visited: set, prev: dict, fringe: queue): valid_nodes = queue() r = matrix_node[0] c = matrix_node[1] grid = self.maze.getGrid() # check if the adjacent nodes are within the bounds of the grid # also check if the adjacent nodes aren't blocked off if r > 0: n = (r - 1, c) if grid[r - 1][c] != 1: n not in visited and n not in prev and n not in fringe and valid_nodes.append(n) if r < self.maze.getDim() - 1: n = (r + 1, c) if grid[r + 1][c] != 1: n not in visited and n not in prev and n not in fringe and valid_nodes.append(n) if c > 0: n = (r, c - 1) if grid[r][c - 1] != 1: n not in visited and n not in prev and n not in fringe and valid_nodes.append(n) if c < self.maze.getDim() - 1: n = (r, c + 1) if grid[r][c + 1] != 1: n not in visited and n not in prev and n not in fringe and valid_nodes.append(n) return valid_nodes
def to_swc(self, fname=None): from collections import deque as queue self.fix_parents() i = 1 # counter of swc line todo = queue([self]) memory = {None: -1} # track line numbers of each element out = [] while todo: a = todo.pop() if a in memory: # duplicate continue todo.extend(a.children) parent = memory[a.parent] memory[a] = i # Columns: id t x y z r pid out.append("%d %d %g %g %g %g %d" % (i, a.t, a.x, a.y, a.z, a.r, parent)) i += 1 out = "\n".join(out) if fname is None: return out f = open(fname, "w") f.write(out) f.close()
def main(): root = Node(0) n1 = Node(1) n2 = Node(2) n3 = Node(3) n4 = Node(4) n5 = Node(5) n6 = Node(6) n7 = Node(7) n8 = Node(8) root.left = n1 root.right = n5 n1.left = n2 n1.right = n3 n3.left = n4 n5.left = n6 n5.right = n7 n7.left = n8 q = queue() q.append(root) bfs(q)
def solution(begin, target, words): if target not in words: return 0 q, dic = queue(), dict() q.append((begin, 0)) # 단어 하나차이걸 set에 저장 set_1 = set() for i in words: if (comparison(i, begin)): set_1.add(i) dic[begin] = set_1 # words 끼리 단어하나 차아나는걸 구해둠 for w in words: set_2 = set() for i in words: if (comparison(i, w)): set_2.add(i) dic[w] = set_2 # 탐색 while q: word, level = q.popleft() for dc in dic[word]: if dc == target: return level + 1 else: q.append((dc, level + 1)) return 0
def _walk_nodes(self, root): pending = queue() pending.append(root) while len(pending): node = pending.popleft() if isinstance(node, Tag): for child in node.children: pending.append(child) yield node
def watershed(a, seeds=None, connectivity=1, mask=None, smooth_thresh=0.0, smooth_seeds=False, minimum_seed_size=0, dams=False, override_skimage=False, show_progress=False): """Perform the watershed algorithm of Vincent & Soille (1991).""" seeded = seeds is not None sel = generate_binary_structure(a.ndim, connectivity) b = a if not seeded: seeds = regional_minima(a, connectivity) if seeds.dtype == bool: seeds = label(seeds, sel)[0] if smooth_seeds: seeds = binary_opening(seeds, sel) if smooth_thresh > 0.0: b = hminima(a, smooth_thresh) if skimage_available and not override_skimage and not dams: return skimage.morphology.watershed(b, seeds, sel, None, mask) elif seeded: b = impose_minima(a, seeds.astype(bool), connectivity) levels = unique(b) a = pad(a, a.max() + 1) b = pad(b, b.max() + 1) ar = a.ravel() br = b.ravel() ws = pad(seeds, 0) wsr = ws.ravel() current_label = 0 neighbors = build_neighbors_array(a, connectivity) level_pixels = build_levels_dict(b) #if show_progress: wspbar = ip.StandardProgressBar('Watershed...') #else: wspbar = ip.NoProgressBar() #for i, level in ip.with_progress(enumerate(levels), #pbar=wspbar, length=len(levels)): for i, level in enumerate(levels): idxs_adjacent_to_labels = queue( [idx for idx in level_pixels[level] if any(wsr[neighbors[idx]])]) while len(idxs_adjacent_to_labels) > 0: idx = idxs_adjacent_to_labels.popleft() if wsr[idx] > 0: continue # in case we already processed it nidxs = neighbors[idx] # neighbors lnidxs = nidxs[(wsr[nidxs] != 0).astype(bool)] # labeled neighbors adj_labels = unique(wsr[lnidxs]) if len(adj_labels) == 1 or len(adj_labels) > 1 and not dams: # assign a label wsr[idx] = wsr[lnidxs][ar[lnidxs].argmin()] idxs_adjacent_to_labels.extend( nidxs[((wsr[nidxs] == 0) * (br[nidxs] == level)).astype(bool)]) return juicy_center(ws)
def bfs(graph, start, goal): que = queue([start]) visited = [] sommet = None while len(que) != 0: sommet = que.popleft() if sommet == goal: visited.append(sommet) break visited.append(sommet) [que.append(i) for i in graph[sommet]] return visited
def canBeSorted(N, a, P, vp): # To create the adjacency list of the graph v = [[] for i in range(N)] # Boolean array to mark the visited nodes vis = [False] * N # Creating adjacency list for undirected graph for i in range(P): v[vp[i][0]].append(vp[i][1]) v[vp[i][1]].append(vp[i][0]) for i in range(N): # If not already visited # then apply BFS if (not vis[i]): q = queue() v1 = [] v2 = [] # Set visited to true vis[i] = True # Push the node to the queue q.append(i) # While queue is not empty while (len(q) > 0): u = q.popleft() v1.append(u) v2.append(a[u]) # Check all the adjacent nodes for s in v[u]: # If not visited if (not vis[s]): # Set visited to true vis[s] = True q.append(s) v1 = sorted(v1) v2 = sorted(v2) # If the connected component does not # contain same elements then return false if (v1 != v2): return False return True
def find_path_bfs(adj_list, from_v, to_v): path = [] vertices_queue = queue([(None, from_v)]) visited = set() while vertices_queue: parrent, vertex = vertices_queue.pop() if vertex not in visited: visited.add(vertex) path += [(parrent, vertex)] if vertex == to_v: return fix_path(path) parrent_child_pairs = [(vertex, v) for v in adj_list[vertex]] vertices_queue.extendleft(parrent_child_pairs)
def resynth(self,sequence): running_list = queue([]) for i, element in enumerate(sequence): wrappedelem = AbstractElement(element,i == len(sequence)-1) if (len(running_list) < self.depth): running_list.append(wrappedelem) if (i == self.depth-1): self.initlists[None] = tuple(running_list) else: self.mappings[tuple(running_list)] = wrappedelem running_list.popleft() running_list.append(wrappedelem) return
def watershed(a, seeds=None, smooth_thresh=0.0, smooth_seeds=False, minimum_seed_size=0, dams=True, show_progress=False, connectivity=1): seeded = seeds is not None sel = generate_binary_structure(a.ndim, connectivity) if smooth_thresh > 0.0: b = hminima(a, smooth_thresh) if seeded: if smooth_seeds: seeds = binary_opening(seeds, sel) b = impose_minima(a, seeds.astype(bool), connectivity) else: seeds = regional_minima(a, connectivity) b = a if seeds.dtype == bool: ws = label(seeds, sel)[0] else: ws = seeds levels = unique(a) a = pad(a, a.max()+1) b = pad(b, b.max()+1) ar = a.ravel() br = b.ravel() ws = pad(ws, 0) wsr = ws.ravel() maxlabel = iinfo(ws.dtype).max current_label = 0 neighbors = build_neighbors_array(a, connectivity) level_pixels = build_levels_dict(a) if show_progress: wspbar = ip.StandardProgressBar('Watershed...') else: wspbar = ip.NoProgressBar() for i, level in ip.with_progress(enumerate(levels), pbar=wspbar, length=len(levels)): idxs_adjacent_to_labels = queue([idx for idx in level_pixels[level] if any(wsr[neighbors[idx]])]) while len(idxs_adjacent_to_labels) > 0: idx = idxs_adjacent_to_labels.popleft() if wsr[idx]> 0: continue # in case we already processed it nidxs = neighbors[idx] # neighbors lnidxs = nidxs[ ((wsr[nidxs] != 0) * (wsr[nidxs] != maxlabel)).astype(bool) ] # labeled neighbors adj_labels = unique(wsr[lnidxs]) if len(adj_labels) > 1 and dams: # build a dam wsr[idx] = maxlabel elif len(adj_labels) >= 1: # assign a label wsr[idx] = wsr[lnidxs][ar[lnidxs].argmin()] idxs_adjacent_to_labels.extend(nidxs[((wsr[nidxs] == 0) * (br[nidxs] == level)).astype(bool) ]) if dams: ws[ws==maxlabel] = 0 return juicy_center(ws)
def greedy_assemble(reads): """Returns a string that is a superstring of the input reads, which are given as a list of strings. The superstring computed is determined by the greedy algorithm as described in HW1, with specific tie-breaking criteria. """ g = AssemblyGraph(reads) q = queue(g.generate_possible_edges()) while g.is_disconnected(): src, dest = edge = q.pop()[ 0:2] # pull out the two vertices, ignore weight if g.outdegree(src) == g.indegree( dest) == 0 and g.does_not_cause_cycle(edge): g.add_edge(*edge) return g.superstring_from_edges()
def caminos_minimos(grafo, origen): q = queue() visitados = set() distancias = {} distancias[origen] = 0 visitados.add(origen) q.appendleft(origen) while bool(q): v = q.pop() for w in grafo.adyacentes(v): if w not in visitados: distancias[w] = distancias[v] + 1 q.appendleft(w) visitados.add(w) return distancias
def __init__(self, config): """ Instantiates a new CommandIngest instance :param config: dictionary of configuration data """ Submodule.__init__(self, "command_ingest", config) self.general_queue = queue() self.processes = { "dispatch": ThreadHandler( target=partial(self.dispatch), name="command_ingest_dispatch", parent_logger=self.logger, ) }
def solution(begin, target, words): q, d = queue(), dict() q.append((begin, 0)) d[begin] = set(filter(lambda x: transistable(x, begin), words)) for w in words: d[w] = set(filter(lambda x: transistable(x, w), words)) while q: cur, level = q.popleft() if level > len(words): return 0 for w in d[cur]: if w == target: return level + 1 else: q.append((w, level + 1)) return 0
def solution(maps): answer = [] couple = [] dx = [1, -1, 0, 0] dy = [0, 0, 1, -1] n = len(maps) m = len(maps[0]) for i, v in enumerate(maps): # 2차원 필드로 만들고 maps[i] = list(v) for i in range(n): # 필드를 돌면서 for j in range(m): if (maps[i][j] != '.'): # 현재 위치가 나라일 경우 name = maps[i][j] # 나라 이름을 기억해 둠 maps[i][j] = '.' # 지난 곳은 방문 처리를 함 q = queue() q.append((i, j)) while len(q) != 0: # 현재 위치로 부터 동서남북으로 BFS 탐색을 시작함 cur = q.popleft() for dir in range(4): ny = cur[0] + dy[dir] nx = cur[1] + dx[dir] if ny < 0 or ny >= n or nx < 0 or nx >= m or maps[ny][ nx] == '.': # 필드 밖에 나가거나 나라가 아닌 경우 예외 처리 continue if maps[ny][nx] == name: # 다음 위치가 현재 나라와 같은 경우 큐에 추가 q.append((ny, nx)) maps[ny][nx] = '.' else: # 다음 위차가 다른 나라일 경우(국경을 공유) c = sorted((name, maps[ny][nx])) if c not in couple: # 중복되지 않게 그 쌍을 저장해놓음 couple.append(c) d = defaultdict(list) # 각 나라에서 국경을 공유하는 나라가 얼마나 있는지 알기 위해 dict 생성 for c in couple: d[c[0]].append(c[1]) max_couple_num = 0 for c in d: # dict 를 돌면서 국경을 공유하는 나라 개수가 가장 많은 경우를 고름 l = len(d[c]) if max_couple_num < l: max_couple_num = l answer.append(len(couple)) answer.append(max_couple_num) return answer
def generate(self): running_list = queue(self.initlists[None]) generated_sequence = [] for elem in running_list: generated_sequence.append(elem.element) if elem.isTerminal: return generated_sequence next_elem = self.mappings[tuple(running_list)] running_list.popleft() running_list.append(next_elem) generated_sequence.append(next_elem.element) while not next_elem.isTerminal: next_elem = self.mappings[tuple(running_list)] running_list.popleft() running_list.append(next_elem) generated_sequence.append(next_elem.element) return generated_sequence
def bfs(graph, v): visited[v] = True arr = queue() arr.append(v) print(v) s, k = 1, 1 while (s): u = arr.popleft() s -= 1 k -= 1 for i in graph[u]: if (not visited[i]): visited[i] = True arr.append(i) s += 1 print(i, end=" ") if (k == 0): k = s print("")
def bfs(node): qu = queue() qu.append([node, -1]) vis[node] = True while (len(qu) > 0): p = qu.popleft() vis[p[0]] = True for child in tree[p[0]]: if (vis[child] == False): qu.append([child, p[0]]) for u in path[p[0]]: path[child].append(u) path[child].append(p[0])
def bracketing_helper(s1, s2): """Adds double square brackets to s1 and s2 for any characters not in the largest common sub-sequence of the two strings""" lcs = queue(longest_common_substring(s1, s2)) lcs2 = copy.deepcopy(lcs) s1_diff = "" s2_diff = "" for c in s1: if len(lcs) > 0 and lcs[0] == c: lcs.popleft() s1_diff += c else: s1_diff += "[[" + c + "]]" for c in s2: if len(lcs2) > 0 and lcs2[0] == c: lcs2.popleft() s2_diff += c else: s2_diff += "[[" + c + "]]" return s1_diff, s2_diff
def __init__(self, ctl, ctx): """Initialize the state machine. Prepares the machine for execution and prepares event processing necessities. Arguments: ctl: a MachineControl instance ctx: the machine's context, a StateMachine """ self.ctl = ctl self.ctx = ctx self.inbox = queue() self.event = None self.is_suspended = False self.init_state = self.halt self.info = []
def bfs(graph, u): n = len(graph) vis = [False] * n vis[u] = True levels = [] q = queue() q.append(u) k = 1 q_size = 1 while (not q_size == 0): k -= 1 if (k == 0): k = q_size levels.append(list(q)) v = q.popleft() q_size -= 1 for i in graph[v]: if not vis[i]: vis[i] = True q.append(i) q_size += 1 return levels
def __init__(self, *args, **kwargs): """Create a base throttler with the given delay time and pool size When both ``delay`` and ``reqs_over_time`` are :const:`None`, :attr:`delay` is set to :const:`0`. :param name: the name of the throttler (default: :const:`None`) :type name: string :param session: the sessions to use for each request :type session: requests.Session :param delay: the fixed positive amount of time that must elapsed bewteen each request in seconds (default: :const:`None`) :type delay: float :param reqs_over_time: a tuple of the form (`number of requests`, `time`) used to calculate the delay to use when it is :const:`None`. The delay will be equal to ``time / number of requests`` (default: :const:`None`) :type reqs_over_time: (float, float) :param max_pool_size: the maximum number of enqueueable requests (default: *unlimited*) :type max_pool_size: int :raise: :ValueError: if ``delay`` or the value calculated from ``reqs_over_time`` is a negative number """ self._name = kwargs.get('name') self._requests_pool = queue(maxlen=kwargs.get('max_pool_size')) self._delay = self._get_delay(kwargs.get('delay'), kwargs.get('reqs_over_time')) self._status = 'initialized' self._session = kwargs.get('session', requests.Session()) self._executor = ThreadPoolExecutor(max_workers=1) self._timer = Timer(checkpoint=0) self._successes = 0 self._failures = 0 self._wait_enqueued = None self.status_lock = threading.Condition(threading.Lock()) self.not_empty = threading.Condition(threading.Lock())
def watershed(a, seeds=None, connectivity=1, mask=None, smooth_thresh=0.0, smooth_seeds=False, minimum_seed_size=0, dams=False, override_skimage=False, show_progress=False): """Perform the watershed algorithm of Vincent & Soille (1991). Parameters ---------- a : np.ndarray, arbitrary shape and type The input image on which to perform the watershed transform. seeds : np.ndarray, int or bool type, same shape as `a` (optional) The seeds for the watershed. If provided, these are the only basins allowed, and the algorithm proceeds by flooding from the seeds. Otherwise, every local minimum is used as a seed. connectivity : int, {1, ..., a.ndim} (optional, default 1) The neighborhood of each pixel, defined as in `scipy.ndimage`. mask : np.ndarray, type bool, same shape as `a`. (optional) If provided, perform watershed only in the parts of `a` that are set to `True` in `mask`. smooth_thresh : float (optional, default 0.0) Local minima that are less deep than this threshold are suppressed, using `hminima`. smooth_seeds : bool (optional, default False) Perform binary opening on the seeds, using the same connectivity as the watershed. minimum_seed_size : int (optional, default 0) Remove seed regions smaller than this size. dams : bool (optional, default False) Place a dam where two basins meet. Set this to True if you require 0-labeled boundaries between different regions. override_skimage : bool (optional, default False) skimage.morphology.watershed is used to implement the main part of the algorithm when `dams=False`. Use this flag to use the separate pure Python implementation instead. show_progress : bool (optional, default False) Show a cute little ASCII progress bar (using the progressbar package) Returns ------- ws : np.ndarray, same shape as `a`, int type. The watershed transform of the input image. """ seeded = seeds is not None sel = generate_binary_structure(a.ndim, connectivity) # various keyword arguments operate by modifying the input image `a`. # However, we operate on a copy of it called `b`, so that `a` can be used # to break ties. b = a if not seeded: seeds = regional_minima(a, connectivity) if minimum_seed_size > 0: seeds = remove_small_connected_components(seeds, minimum_seed_size, in_place=True) seeds = relabel_from_one(seeds)[0] if smooth_seeds: seeds = binary_opening(seeds, sel) if smooth_thresh > 0.0: b = hminima(a, smooth_thresh) if seeds.dtype == bool: seeds = label(seeds, sel)[0] if skimage_available and not override_skimage and not dams: return skimage.morphology.watershed(b, seeds, sel, None, mask) elif seeded: b = impose_minima(a, seeds.astype(bool), connectivity) levels = unique(b) a = pad(a, a.max()+1) b = pad(b, b.max()+1) ar = a.ravel() br = b.ravel() ws = pad(seeds, 0) wsr = ws.ravel() neighbors = build_neighbors_array(a, connectivity) level_pixels = build_levels_dict(b) if show_progress: wspbar = ip.StandardProgressBar('Watershed...') else: wspbar = ip.NoProgressBar() for i, level in ip.with_progress(enumerate(levels), pbar=wspbar, length=len(levels)): idxs_adjacent_to_labels = queue([idx for idx in level_pixels[level] if any(wsr[neighbors[idx]])]) while len(idxs_adjacent_to_labels) > 0: idx = idxs_adjacent_to_labels.popleft() if wsr[idx] > 0: continue # in case we already processed it nidxs = neighbors[idx] # neighbors lnidxs = nidxs[(wsr[nidxs] != 0).astype(bool)] # labeled neighbors adj_labels = unique(wsr[lnidxs]) if len(adj_labels) == 1 or len(adj_labels) > 1 and not dams: # assign a label wsr[idx] = wsr[lnidxs][ar[lnidxs].argmin()] idxs_adjacent_to_labels.extend(nidxs[((wsr[nidxs] == 0) * (br[nidxs] == level)).astype(bool) ]) return juicy_center(ws)