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)
Пример #2
0
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_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')
Пример #4
0
    def cal(self, stack):
        operators = []
        result = 0
        current_num = 0
        while stack:
            c = stack.pop()
            if c.isdigit():
                current_num = current_num * 10 + int(c)
            else:
                if current_num != 0 and not operators:
                    result = current_num
                    current_num = 0

                if c == "+" or c == "-":
                    if operators:
                        result = caculate(result, operators.pop(), current_num)
                        current_num = 0
                        operators.append(c)
                    else:
                        operators.append(c)
                elif c == "(":
                    if operators:
                        result = caculate(result, operators.pop(),
                                          self.cal(stack))
                    else:
                        result = self.cal(stack)
                elif c == ")":
                    break
        if operators:
            result = caculate(result, operators.pop(), current_num)
        elif not result:
            return current_num
        return result
Пример #5
0
def depthFirstSearch(problem):
    """
    Search the deepest nodes in the search tree first.

    Your search algorithm needs to return a list of actions that reaches the
    goal. Make sure to implement a graph search algorithm.

    To get started, you might want to try some of these simple commands to
    understand the search problem that is being passed in:

    print "Start:", problem.getStartState()

    """
    "*** YOUR CODE HERE ***"
    start = problem.getStartState()  #present state
    stack = util.Stack(
    )  #stack to hold present state and directions from Start state
    visited_set = []  # list containing all visited nodes
    start_dir = []  # Entire path from start to the goal path
    while (problem.isGoalState(start) != True):
        successors = problem.getSuccessors(start)
        start_dir_len = len(start_dir)
        for l, m, n in successors:
            temp = start_dir[0:start_dir_len]
            temp.append(m)
            stack.push((l, temp))
        while True:
            start, start_dir = stack.pop(
            )  #Getting the successor to be explored and the directions from start node
            if start not in visited_set:  #If the successor is in the visited set get the next successor
                visited_set.append(start)
                break
    return start_dir
Пример #6
0
 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))
Пример #7
0
def string_reverse(string):
    stack = Stack()
    start, start_ = 0, 0
    reversed_str = ""
    while start < len(string):
        index = string[start]
        stack.push(index)
        start += 1
    while start_ < len(string):
        reversed_str += stack.pop()
        start_ += 1
    return reversed_str
Пример #8
0
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 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))
Пример #10
0
 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
Пример #11
0
    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
Пример #12
0
 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
Пример #13
0
 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)
Пример #15
0
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 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))
Пример #17
0
    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
Пример #18
0
            self._content.append(v)
            self._current = self._current + 1
        else:
            print('Stack Full!')

    def pop(self):
        if self._content:
            self._current = self._current - 1
            return self._content.pop()
        else:
            print('Stack empty!')

    def show(self):
        print(self._content)

    def showRemainderSpace(self):
        print('Stack can still push ', self._size-self._current, 'elements.')

if __name__ == '__main__':
    print('Please use me as a module.')
    stack = myStack(10)
    for i in range(1,6):
        stack.push(i)
    stack.show()
    stack.showRemainderSpace();
    for i in range(0,4):
        stack.pop()
    print(stack.isEmpty())
    stack.show();
    stack.pop()
    print(stack.isEmpty())
Пример #19
0
@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)

find(4)
Пример #20
0
def test_pop_raise_empty():  # 7
    stack = Stack()
    actual = stack.pop()
    expected = 'empty stack'
    assert actual == expected