def iter_deep(self): """ Iterative Deepening Search """ for depth in range(1, DEPTH_LIMIT): solution = self.search(Stack(), False, depth) if solution.is_success(): return solution return Solution()
def pressHotKeys(self, keys): #make a stack stack = Stack() temp = 0 for key in keys: try: if key["type"] == 1: # if is special type if key["value"] in self.SpecialKeyCodes: temp = self.SpecialKeyCodes[key["value"]] gui.keyDown(temp) stack.put(temp) else: temp = key["value"] if len(temp) == 1: gui.keyDown(temp) stack.put(temp) except: pass #empty the stack #unpress the key in the opposite order they were pressed while not stack.empty(): temp = stack.get() gui.keyUp(temp)
def scoreOfParentheses(self, S: str) -> int: # stack = Stack() # for ltr in S: # if ltr == '(': # stack.put(0) # else: # val = stack.get() # if stack.qsize() > 0: # if val == 0: # prev = stack.get() # prev += 1 # stack.put(prev) # else: # prev = stack.get() # prev += val*2 # stack.put(prev) # else: # if val == 0: # stack.put(1) # else: # stack.put(val*2) # return stack.get() cur_level = 0 stack = Stack() for ltr in S: if ltr == '(': stack.put(cur_level) cur_level = 0 else: maxx = max(1, cur_level) cur_level += stack.get() + maxx return(cur_level)
class Solution: def validTree(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: bool """ if len(edges) != n-1: return False dic = defaultdict(list) for x, y in edges: assert(isinstance(x, int) and isinstance(y, int)) dic[x].append(y) dic[y].append(x) stack = Stack() stack.put(0) visited = set([0]) while not stack.empty(): node = stack.get() visited.add(node) for child in dic[node]: if child not in visited: stack.put(child) return len(visited) == n
def DFS(self, initial_state): start_node = Node(initial_state, None, None, 0, initial_state.index(0)) if start_node.goal_test().all(): return start_node.find_solution() frontier = Stack() ## List Stack frontier.put(start_node) explored = [] ## Needs changing, change to set(). star = "**********************************" print("\nInitial State ---------- Depth: {0}".format(start_node.depth)) while not (frontier.empty()): node = frontier.get() print("--------------------------------------------------") if node.goal_test().all(): print("***************GOAL STATE FOUND*******************") print("\n") print(node.display()) return node print("Depth = {0} \n".format(node.depth)) print("{0}".format(node.display())) print(star) explored.append(node.state) children = node.generate_child() for child in children: if child.state not in explored: frontier.put(child) return
def __init__(self): """Create the app.""" super().__init__() self.configure_window() self.screen_stack = Stack( ) #Here the window will save a reference and order of the screens that it has packed #So that they can unpacked accordingly. self.pack_help_frame( ) #This frame provides help and a button to go to the previous window self.pack_initial_screen() #Calling method to setup the initial screen
def dfs(graph, start, goal): visited = set() stack = Stack() stack.put(start) while not stack.empty(): node = stack.get() if node == goal: return True visited.add(node) for child in graph[node]: if child not in visited: stack.put(child) return False
def _display_dfs(self): if not self.root: return None container = Stack() container.put(self.root) while not container.empty(): node = container.get() for i, child in enumerate(node.children): if child == None: continue if any(child.children): container.put(child) print(i, ":", child.key, end=", ") print('\n')
class z9c(Serial): recv_buffer = Stack(maxsize=200) send_buffer = Stack(maxsize=200) dev = "" baud = "" def __init__(self, dev, baud=115200, async_mode=False): self.dev, self.baud = dev, baud super().__init__(port=self.dev, baudrate=self.baud) self.logger = logging.getLogger() self.logger.info(f"Initialized Device {dev} @Baudrate {baud}") self.connection = False self.try_timeout = 50 self.id = str(uuid4()) self.logger.info( f"Created Serial Device for resource {dev} as ID:{self.id}") self.establish_connection() self.async_mode = async_mode def clear_device_buffer(self): logging.debug("Clearing Device Buffer") while (out := self.recv())[1] == "ACK": continue
def isValid(self, s): if not s: return True n = len(s) if n % 2 == 1: return False q = Stack(maxsize=n) for c in s: if isOpen(c): q.put(c) elif q.empty() or OP[c] != q.get(): return False return q.empty()
def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode: """ Finds the lowest common ancestor of the given nodes in the tree. :param root: The root of the tree. :param p: TreeNode whose lowest common ancestor with q is to be found. :param q: TreeNode whose lowest common ancestor with p is to be found. :return: The lowest common ancestor of p and q if there is one. """ # We use a stack to traverse the tree. stack = Stack() stack.put(root) # Dictionary to track the parents of each node. parents = {root: None} # We keep populating the parents dictionary till we haven't seen both # p and q. while p not in parents or q not in parents: # Get the node to be visited from the stack. node = stack.get() # Update the nodes children's parent and populate the stack if node.left: parents[node.left] = node stack.put(node.left) if node.right: parents[node.right] = node stack.put(node.right) # Set to hold unique ancestors as we traverse back along the parents # dictionary. ancestors = set() # Traverse upwards from p to the root of the tree and saving the path of # ancestors traversed along. while p: ancestors.add(p) p = parents[p] # Traverse upwards from q till we dont find a common ancestor in the path. while q not in ancestors: ancestors.add(q) q = parents[q] # return q if found else, q would be None. return q
def dfs(self, key): """ return node if found return None if not found """ if not self.root: return None stack = Stack() stack.put(self.root) while not stack.empty(): node = stack.get() if key == node.key: return node for child in node.children[::-1]: stack.put(child) return None
def check_balance(word): stack_validator = Stack() for i in word: if i == '(' or i == '[' or i == '{': stack_validator.put(i) else: if i == ')': if stack_validator.get() != '(': return False elif i == ']': if stack_validator.get() != '[': return False elif i == '}': if stack_validator.get() != '{': return False if stack_validator.empty(): return True else: return False
def hasCycle(self, graph): # return True if graph has cycle, else return False visited = set() for node in graph.keys(): if node not in visited: stack = Stack() stack.put(node) path = set([node]) while not stack.emtpy(): node = stack.pop() visited.add(node) for child in graph[node]: if child in path: return True if child not in visited and child in graph: stack.append(child) path.add(child) if len(visited) == len(graph): break return False
def countComponents(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: int """ """ Time: O(n) Space: O(n) """ # input validation if n == 0 and len(edges) == 0: return 0 if n != 0 and len(edges) == 0: return n assert(isinstance(n, int) and 0 < n) # initialization dic = defaultdict(list) for vi, vj in edges: dic[vi].append(vj) dic[vj].append(vi) visited = set() count = 0 # process for i in range(n): if i in dic and i not in visited: stack = Stack() stack.put(i) while not stack.empty(): node = stack.get() visited.add(node) for child in dic[node]: if child not in visited: stack.put(child) count += 1 return count + (n - len(visited))
def up_link_down(sibling): letters = Stack() while sibling and not sibling.link: letters.put(sibling.parent_letter) sibling = sibling.parent if not sibling: return None, None node = sibling.link while not letters.empty(): curr_letter = letters.get() if curr_letter in node.children: node = node.children[curr_letter] sibling = sibling.children[curr_letter] sibling.link = node else: break return node, sibling
def dfs(problem): open_set = Stack() # LIFO open_set closed_set = set() # visited nodes set meta = dict() # meat information, meta[key] = (parent_state, action to reach child) # Initialize root = problem.get_root() meta[root] = (None, None) open_set.put(root) while not open_set.empty(): node = open_set.get() if problem.isGoal(node): return construc_path(node, meta) for (child, action) in problem.getSuccessors(node): if child in closed_set: continue if child not in open_set: meta[child] = (node, action) open_set.put(child) closed_set.add(node)
def DLFS(self, initial_state, Depth): start_node = Node(initial_state, None, None, 0) start = time.time() ## if start_node.goal_test().all(): return start_node.find_solution() frontier = Stack() ## List Stack frontier.put(start_node) explored = set() print("\nInitial State ---------- Depth: {0}".format(start_node.depth)) while not (frontier.empty()): if DLFS.searchCanceled: print("canceled!") return self.max_stored = max(self.max_stored, frontier.qsize() + len(explored)) node = frontier.get() if node.goal_test().all(): print("***************GOAL STATE FOUND*******************") print("\n") print(node.display()) DLFS.pathCost = node.depth ## DLFS.maxStoredNodes = self.max_stored ## DLFS.numProcessedNodes = node.num_processed ## DLFS.timeTaken = time.time() - start ## return node.find_solution() if (node.depth < Depth and tuple(node.state) not in explored): explored.add(tuple(node.state)) children = node.generate_child() for child in children: if DLFS.searchCanceled: print("canceled!") return if tuple(child.state) not in explored: frontier.put(child) return None
def make_dfs(g: Graph): stack = Stack() visited = set() for v_idx in g.get_vertexes(): if v_idx in visited: continue stack.put(v_idx) while (not stack.empty()): curr_v = stack.get() stack.put(curr_v) # just peek, not pop has_unvisited_neighbor = False if curr_v not in visited: yield curr_v visited.add(curr_v) for neighbor_idx in g.get_neighbors(curr_v): if neighbor_idx in visited: continue stack.put(neighbor_idx) has_unvisited_neighbor = True break if has_unvisited_neighbor: continue stack.get() # pop
def calPoints(self, ops: List[str]) -> int: stack = Stack() accum = 0 for op in ops: try: stack.put(int(op)) accum += int(op) except: if op == 'C': last_valid = stack.get() accum -= last_valid elif op == 'D': last_valid = stack.get() accum += last_valid * 2 stack.put(last_valid) stack.put(last_valid * 2) elif op == "+": last_valid = stack.get() before_last = stack.get() accum += (last_valid + before_last) stack.put(before_last) stack.put(last_valid) stack.put(before_last + last_valid) return accum
def __init__(self): LOGGER.debug(f"{self}") super(GPIOHypervisor, self).__init__() self.cmd = Stack(maxsize=4) self.logger = logging.getLogger("GPIO Hypervisor")
def __init__(self): LOGGER.debug(f"{self}") self.SEND = Stack(maxsize=256) self.CMD = Stack(maxsize=256)
def __init__(self, target): self.target = target self.RECV = Stack(maxsize=256) self.SEND = Stack(maxsize=256)
def __init__(self): self.stak = Stack() self.q = Queue()
def dfs(self): """ Depth-First Search """ return self.search(Stack())
def __init__(self): self.q = Stack()
def __init__(self): self.stack = Stack() self.top = None
def partition(self, s: str): path = Stack() result = [] self.recursion(s, 0, len(s), path, result) return result