def import_outline(a=None): ''' Arg: <outline.txt> - convert tree text to graph Ex2: \"write_dot(import_outline('outline.txt'),'outline.dot')\" ''' cf = my_graph() stack = list() nprev = -1 with open(a, 'r') as f: for line in f: m = re.match(r'^([\t ]*)(.*)', str(line)) if m: n = len(m.group(1)) id = str(m.group(2)) else: raise Exception(line) if not id: continue id = re.sub(' \^$', '', id) if n <= nprev: stack = stack[:n - nprev - 1] # print(n, id, stack) if id not in ignores: if len(stack): cf.add_edge(stack[-1], id) stack.append(id) nprev = n return cf
def fit(self, X, y): from numpy import zeros, hstack, ones, allclose, matmul X = self._scale(X) if self.scale else X m = X.shape[0] θ = zeros(shape=X.shape[-1] + 1) X = hstack([ones(m)[:, None], X]) α = self.learning_rate # learning rate k = 5 # how many pockets in the deque aka stack-array should be stack = __import__('collections').deque(maxlen=k) for loop in range(int(3e+5)): theta_old = θ.copy() θ -= α * (matmul(matmul(X, θ) - y, X) / m) b = allclose(θ, theta_old, rtol=1e-6) stack.append(b) if len(stack) >= k and set(stack) == {True}: break else: from warnings import warn warn("maximum number of loops reached: %g" % loop, Warning) self.loops = loop + 1 self._weights = θ return self
def dfs_matrix_rec_path_two(self, map, graph, stack, visited, goal): if stack: last_path = stack.pop() last_node = last_path[-1] if last_node not in visited: visited.append(last_node) if last_node == goal: print('->'.join(last_path)) return last_path current_node_key = -1 for key, value in map.items(): if value == last_node: current_node_key = key neighbours_loc = graph[current_node_key] index = 0 while index < len(neighbours_loc): if neighbours_loc[index] == 1: neighbour = map[index] if neighbour not in visited: new_last_path = list(last_path) new_last_path.append(neighbour) stack.append(new_last_path) index += 1 self.dfs_matrix_rec_path_two(map, graph, stack, visited, goal) else: print('Cant find goal')
def import_cflow(a=None, cflow_out=None): # Arg: $none_or_dir_or_file_or_mask cf = my_graph() stack = list() nprev = -1 cflow_out = open(cflow_out, 'w') if cflow_out else None for line in cflow(a): if cflow_out: cflow_out.write(line + '\n') # --print-level m = re.match(r'^([\t]*)([^(^ ^<]+)', str(line)) if m: n = len(m.group(1)) id = str(m.group(2)) else: raise Exception(line) if n <= nprev: stack = stack[:n - nprev - 1] # print(n, id, stack) if id not in ignores: if len(stack): cf.add_edge(stack[-1], id) stack.append(id) nprev = n return cf
def store_as_stack(s): stack = [] i = len(s) - 1 while i > -1: stack.append(s[i]) i -= 1 return stack
def minRemoveToMakeValid(self, s: str) -> str: s = list(s) par_mapping = {')': '(', ']': '[', '}': '{'} open_par = set(par_mapping.values()) stack = [] for i, char in enumerate(s): if char in open_par: stack.append(i) elif char in par_mapping: if stack: expected = par_mapping[char] if s[stack[-1]] == expected: stack.pop() else: s[i] = '' else: s[i] = '' while stack: s[stack[-1]] = '' stack.pop() return ''.join(s)
def parentheses(s): stack = [] for ch in s: if stack and is_sym(ch, stack[len(stack) - 1]): stack.pop() else: stack.append(ch) if stack: return False return True
def dfs_expand_path(self, graph, stack, visited): if stack: last_node = stack.pop() if last_node not in visited: visited.append(last_node) neighbours = graph[last_node] for neighbour in neighbours: if neighbour not in visited: stack.append(neighbour) self.dfs_expand_path(graph, stack, visited) else: print('->'.join(visited))
def inorderTraversal2(self, root): if not root: return [] list, stack = [], [] while root or stack: while root: stack.append(root) root = root.left root = stack.pop() list.append(root.val) root = root.right return list pass
def dfs_graph_vetex(self, graph, root): visited = [] stack = [root] while stack: vertex = stack.pop() if vertex not in visited: visited.append(vertex) neighbours = graph[vertex] for neighbour in neighbours: if neighbour not in visited: stack.append(neighbour) print('->'.join(visited))
def preorderTraversal4(self, root): if not root: return [] list = [] stack = [] while root: list.append(root.val) if root.right: stack.append(root.right) root = root.left if not root and stack: root = stack.pop() return list
def dfs_goal_path(self, graph, stack, visited, goal): if stack: last_path = stack.pop() last_node = last_path[-1] if last_node == goal: print('->'.join(last_path)) return last_path if last_node not in visited: visited.append(last_node) neighbours = graph[last_node] for neighbour in neighbours: if neighbour not in visited: new_last_path = list(last_path) new_last_path.append(neighbour) stack.append(new_last_path) self.dfs_goal_path(graph, stack, visited, goal)
def dfs_path_goal(self, graph, root, goal): visited = [] stack = [root] while stack: last_path = stack.pop() last_node = last_path[-1] if last_node == goal: print('->'.join(last_path)) return last_path if last_node not in visited: visited.append(last_node) for neighbour in graph[last_node]: if neighbour not in visited: new_path = list(last_path) new_path.append(neighbour) stack.append(new_path)
def dfs_extendpath_rec_matrix(self, map, graph, stack, visited): if stack: last_node = stack.pop() if last_node not in visited: visited.append(last_node) current_node_key = -1 for key, value in map.items(): if value == last_node: current_node_key = key neighbours_loc = graph[current_node_key] index = 0 while index < len(neighbours_loc): if neighbours_loc[index] == 1: neighbour = map[index] if neighbour not in visited: stack.append(neighbour) index += 1 self.dfs_extendpath_rec_matrix(map, graph, stack, visited) else: print('->'.join(visited))
def isLeagal(str): stack = [] A = ['[', '(', '{'] B = [']', ')', '}'] for s in str: if s in A: stack.append(s) else: if len(stack) > 0: a = stack.pop() if isPair(a, s, A, B): continue else: return False else: return False if len(stack) > 0: return False return True
def remove_loops(dg): rm = [] visited = set() path = [object()] path_set = set(path) stack = [iter(dg)] while stack: for v in stack[-1]: if v in path_set: rm.append((path[-1], v)) elif v not in visited: visited.add(v) path.append(v) path_set.add(v) stack.append(iter(dg[v])) break else: path_set.remove(path.pop()) stack.pop() # print(rm) dg.remove_edges_from(rm) return dg
def isValid(self, s): """ :type s: str :rtype: bool """ p_table = {"(": ")", "[": "]", "{": "}"} stack = [] for c in s: print(f'{c}') # 左括號押入 stack if c in p_table.keys(): stack.append(c) else: # 右括號, 取出 stack popUp 的左括號 pop_c = stack.pop() # 檢查 popUp 的左括號對應的右括號是否相同 if c != p_table[pop_c]: return False # 如果 stack 不為空, 代表 s 為不合法字串 return not stack
def import_outline(a=None): cf = my_graph() stack = list() nprev = -1 with open(a, 'r') as f: for line in f: m = re.match(r'^([\t ]*)(.*)', str(line)) if m: n = len(m.group(1)) id = str(m.group(2)) else: raise Exception(line) if not id: continue id = re.sub(' \^$', '', id) if n <= nprev: stack = stack[:n - nprev - 1] # print(n, id, stack) if id not in black_list: if len(stack): cf.add_edge(stack[-1], id) stack.append(id) nprev = n return cf
def preorderTraversal3(self, root): if not root: return [] list = [] stack = [] stack.append(root) while stack: node = stack.pop() list.append(node.val) if node.right: stack.append(node.right) if node.left: stack.append(node.left) return list pass
''' Created on 04-Apr-2020 @author: HP ''' #TODO: create a stack from inspect import stack stack = [] #TODO: insert items into stack stack.append(1) stack.append(2) stack.append(3) stack.append(4) #TODO: print the stack print(stack) #TODO: find element in a stack def find(val): if val in stack: print('value found', val) else: print('value not found', val) #TODO: delete an item x = stack.pop() print(x) print(stack)
#print "\n\nprint_exc\n",traceback.print_exc() #print "\n\nextract_stack\n",traceback.extract_stack() #print "\n\nprint_last\n",traceback.print_last() error_type,error_value,tb = exc_info() #print type(exc_info()) #print "\n\nexc_info\n",exc_info() #print "Error type:",error_type print "Error type:",error_type print "Traceback",tb while tb.tb_next: tb = tb.tb_next stack = [] f = tb.tb_frame while f: stack.append(f) f = f.f_back stack.reverse() for frame in stack: print "\n\nFrame: %s" % (frame.f_code.co_name) print "File: %s" % (path.split(frame.f_code.co_filename)[1]) print "Path: %s" % (frame.f_code.co_filename) print "Line#: %s" % (frame.f_lineno) print "Code: %s" % getline(path.split(frame.f_code.co_filename)[1], frame.f_lineno) for key,value in frame.f_locals.items(): print "\t%20s= " % key, try: print value except: print "error printing value"