Esempio n. 1
0
def sort(stack):
    new_stack = Stack()
    length = stack.length
    print(length)
    for _ in range(length):
        min_value = get_min(stack)
        # print(min_value)
        new_stack.push(min_value)
        remove(stack, min_value)
    print(new_stack)
Esempio n. 2
0
class Queue:
    """
    Очередь реализованная на 2 стеках

    При size = 0 push и pop вернет None
    """
    def __init__(self):
        self._stack_inp = Stack()  # для того чтобы складывать элементы
        self._stack_out = Stack()  # для извлечения элементов
        self.size = 0

    def push(self, value):
        """Добавить в очередь value"""
        self._stack_inp.push(value)
        self.size += 1
        return None

    def pop(self):
        """Извлечь из очереди первый элемент"""
        if self.size == 0:
            result = None

        elif self._stack_out.size != 0:
            result = self._stack_out.pop()
            self.size -= 1

        else:
            self._move_all_elements_from_inp_to_out()
            result = self._stack_out.pop()
            self.size -= 1

        return result

    def front(self):
        """Вернуть первый элемент в очереди без извлечения"""
        if self.size == 0:
            result = None

        elif self._stack_out.size != 0:
            result = self._stack_out.back()

        else:
            self._move_all_elements_from_inp_to_out()
            result = self._stack_out.back()

        return result

    def _move_all_elements_from_inp_to_out(self):
        """Переместить все элементы из входного стека в выходной"""
        while self._stack_inp.size != 0:
            val = self._stack_inp.pop()
            self._stack_out.push(val)
        return None
Esempio n. 3
0
def test_push():
    stack = Stack()

    stack.push(1)
    assert stack.back() == 1
    assert stack.size == 1

    stack.push(3)
    assert stack.back() == 3
Esempio n. 4
0
def is_brace_balanced(expr):
    assert isinstance(expr, str), 'argument must be of str type'
    stack = Stack()
    for char in expr:
        if char in "{[(":
            stack.push(char)
        elif char in "}])":
            if (not stack.is_empty()) and is_pair(stack.top(), char):
                stack.pop()
            else:
                return False

    return stack.is_empty()
Esempio n. 5
0
def main():
    stack = Stack()
    stack.push_all([6, 4, 2, 1, 3, 5, 56, 66])
    print(stack)
    # print(get_min2(stack, stack.peek()))
    # value = get_min(stack)
    # print(value)
    # remove(stack, value)
    # print(stack)
    # for _ in range(6):
    #     min_value = get_min(stack)
    #     print("min_value:{0}".format(min_value))
    #     print("stack:{0}".format(stack))
    #     remove(stack, min_value)
    #     print("stack:{0}".format(stack))
    #     print("====================")
    sort(stack)
Esempio n. 6
0
def test_pop():
    stack = Stack()

    stack.push(1)
    assert stack.size == 1
    assert stack.pop() == 1
    assert stack.size == 0

    stack.push(3)
    stack.push(1)
    assert stack.pop() == 1
    assert stack.size == 1
    assert stack.pop() == 3
    assert stack.size == 0
Esempio n. 7
0
def eval_prefix(expr):
    s = Stack()
    for c in expr[::-1]:  # from right to left
        if c in oper:
            a = int(s.pop())  # notice the order of a, b
            b = int(s.pop())
            s.push(oper[c](a, b))
        else:
            s.push(c)

    return s.pop()
Esempio n. 8
0
def eval_postfix(expr):
    s = Stack()
    for c in expr:
        if c in oper:
            b = int(s.pop())
            a = int(s.pop())
            s.push(oper[c](a, b))
        else:
            s.push(c)

    return s.pop()
Esempio n. 9
0
 def dfs_iter(self, grp, src):
     vtx = [0] * len(grp)
     stk = Stack()
     vtx[src] = 1
     stk.push(src)
     while len(stk) > 0:
         i = stk.pop()
         assert (vtx[i] == 1)
         for j in grp[i]:
             if vtx[j] == 0:
                 stk.push(i)
                 vtx[j] = 1
                 stk.push(j)
                 break
     return vtx
Esempio n. 10
0
def sort_stack2(stack):
    if stack.is_empty():
        return stack
    new_stack = Stack()
    while not stack.is_empty():
        cur = stack.pop()
        while (not new_stack.is_empty()) and (new_stack.peek() > cur):
            stack.push(new_stack.pop())
        new_stack.push(cur)
    return new_stack
Esempio n. 11
0
def decimal_to_binary_stack(decimal):
    s = Stack()
    while decimal > 1:
        mod = decimal % 2
        s.push(mod)
        div = decimal / 2
        decimal = div
    s.push(decimal)

    # convert stack to a string
    result = []
    while not s.is_empty():
        result.append(str(s.pop()))
    return "".join(result)
Esempio n. 12
0
 def dfs_iter(self, grp, src):
     vtx = [0] * len(grp)
     stk = Stack()
     vtx[src] = 1
     stk.push(src)
     while len(stk) > 0:
         i = stk.pop()
         assert (vtx[i] == 1)
         for j in grp[i]:
             if vtx[j] == 0:
                 stk.push(i)
                 vtx[j] = 1
                 stk.push(j)
                 break
     return vtx
Esempio n. 13
0
    def isValid(self, s):
        # unbalance number of parentheses
        if len(s) % 2 != 0:
            return False

        left_parentheses = '([{'
        right_parentheses = ')]}'
        stack = Stack()

        for c in s:
            # it is not a left parentheses
            if c in left_parentheses:
                stack.push(c)
            # it is a right parentheses
            elif stack.isEmpty(
            ) or stack.peek() != left_parentheses[right_parentheses.index(c)]:
                return False
            else:
                stack.pop()

        return stack.isEmpty()
def decimal_to_binary_stack(decimal):
    s = Stack()
    while decimal > 1:
        mod = decimal % 2
        s.push(mod)
        div = decimal / 2
        decimal = div
    s.push(decimal)

    # convert stack to a string
    result = []
    while not s.is_empty():
        result.append(str(s.pop()))
    return "".join(result)
Esempio n. 15
0
 def bracket_match(self, s):
     """
     :param s: str
     :return: bool
     """
     dic = {')':'(', '}':'{', ']':'['}
     stack = Stack()
     for i in s:
         if i in {'{', '[', '('}:
             stack.push(i)
         else:
             if stack.get_top() == dic[i]:
                 stack.pop()
             else:
                 return False
     if stack.is_empty():
         return True
     else:
         return False
Esempio n. 16
0
    def isValid(self, s):
        # unbalance number of parentheses
        if len(s) % 2 != 0:
            return False

        left_parentheses = '([{'
        right_parentheses = ')]}'
        stack = Stack()

        for c in s:
            # it is not a left parentheses
            if c in left_parentheses:
                stack.push(c)
            # it is a right parentheses
            elif stack.isEmpty() or stack.peek() != left_parentheses[right_parentheses.index(c)]:
                return False
            else:
                stack.pop()

        return stack.isEmpty()
Esempio n. 17
0
def dfs(initial, goal_test, successors):
    frontier = Stack()
    frontier.push(Node(initial))
    explored = {initial}

    while not frontier.empty:
        node = frontier.pop()

        if goal_test(node.state):
            return node

        for parent in successors(node.state):
            if parent in explored:
                continue

            explored.add(node.state)
            frontier.push(Node(parent, node))

    return None
Esempio n. 18
0
class TestStack(unittest.TestCase):
    
    def setUp(self):
        self.stack = Stack()
    
    def tearDown(self):
        self.stack = None
    
    def push_test_values(self):
        self.stack.push(1)
        self.stack.push(2)
        self.stack.push(3)
    
    def test_pop(self):
        self.push_test_values()
        self.assertEqual(self.stack.pop().value, 3)
        self.assertEqual(self.stack.pop().value, 2)
        self.assertEqual(self.stack.pop().value, 1)
        
    def test_is_empty(self):
        self.assertTrue(self.stack.is_empty())
        self.push_test_values()
        self.assertFalse(self.stack.is_empty())
def solution():
    init_state = State(3, 3, 1)
    goal_state = State(0, 0, 0)
    state_stack = Stack()
    state_stack.push(init_state)
    visited = {init_state: True}

    while not state_stack.is_empty:
        curr_state = state_stack.pop()

        for action in actions():
            if curr_state.b == 1:
                new_state = curr_state - action
            else:
                new_state = curr_state + action
            if is_valid_state(new_state) and new_state not in visited:
                visited[new_state] = True
                curr_state.next_states.append(new_state)
                state_stack.push(new_state)

            if new_state == goal_state:
                return init_state
    return []
Esempio n. 20
0
def infix_to_prefix(expr):
    prec = {
        ')': 0,
        '+': 1,
        '-': 1,
        '*': 2,
        '/': 2
    }
    output = deque()
    s = Stack()
    # Process starting from the last item
    for c in expr[::-1]:
        if c == ')':
            s.push(c)
        elif c == '(':
            while not s.is_empty() and s.top() != ')':
                output.appendleft(s.pop())
            s.pop()
        elif c in prec:
            # notice it is not >= here, as we handling from right to left
            # so if it is equal, the one comes at left should handled first
            while not s.is_empty() and prec[s.top()] > prec[c]:
                output.appendleft(s.pop())
            s.push(c)
        else:
            output.appendleft(c)

    while not s.is_empty():
        output.appendleft(s.pop())

    return "".join(output)
Esempio n. 21
0
import pathmagic  # noqa
from data_structure.stack import Stack


def delete_middle_from_stack(stack, middle):
    if stack.size() == middle:
        stack.pop()
        return
    end = stack.pop()
    delete_middle_from_stack(stack, middle)
    stack.push(end)


if __name__ == "__main__":
    stack = Stack()
    arr = [1, 2, 3, 4, 5]
    for num in arr:
        stack.push(num)
    middle = int(stack.size() / 2) + 1
    delete_middle_from_stack(stack, middle)
    stack.show()
Esempio n. 22
0
def infix_to_postifx(expr):
    """
    convert infix to postfix

    Args:
        expr: an infix expression in the form of '1 * ( 2 + 3 )'.

    Returns:
        An postfix expression of the same form.
    """
    # precedence dict
    prec = {"^": 4, "*": 3, "/": 3, "+": 2, "-": 2, "(": 1}

    stack = Stack()
    tokens = expr.split()

    postfix_expr = []
    for token in tokens:
        # Find a left parenthesis
        if token == '(':
            stack.push(token)
        # Find a right parenthesis
        elif token == ')':
            top_token = stack.pop()
            while top_token != '(':
                postfix_expr.append(top_token)
                top_token = stack.pop()
        # Find an operator
        elif token in prec:
            while not stack.isEmpty() and prec[stack.peek()] >= prec[token]:
                postfix_expr.append(stack.pop())
            stack.push(token)
        # Find an operand
        else:
            postfix_expr.append(token)

    while not stack.isEmpty():
        postfix_expr.append(stack.pop())
    return " ".join(postfix_expr)
Esempio n. 23
0
Задача B. Правильная скобочная последовательность

Программа получает на вход последовательность из скобок
(открывающихся и закрывающихся скобок трех видов).
Длина последовательности не превышает 255 символов.
Последовательность не содержит пробелов
(но после последнего символа могут идти пробелы и переходы на новую строку).
"""
from data_structure.stack import Stack

OPENING_BRACKETS = ["(", "[", "{"]

BRACKETS_MAPPING = {")": "(", "]": "[", "}": "{"}

inp = input().strip()
stack = Stack()
result = None

for bracket in inp:
    if bracket in OPENING_BRACKETS:
        stack.push(bracket)
    else:
        if BRACKETS_MAPPING[bracket] != stack.pop():
            result = "no"
            break

if stack.size == 0 and not result:
    result = "yes"
else:
    result = "no"
Esempio n. 24
0
def infix_to_postfix(expr):
    prec = {
        '(': 0,
        '+': 1,
        '-': 1,
        '*': 2,
        '/': 2
    }
    output = []
    s = Stack()
    # handle differently for 4 cases
    for c in expr:
        if c == '(':
            s.push(c)
        elif c == ')':
            while not s.is_empty() and s.top() != '(':
                output.append(s.pop())
            s.pop()
        elif c in prec:
            while not s.is_empty() and prec[s.top()] >= prec[c]:
                output.append(s.pop())
            s.push(c)
        else:
            output.append(c)

    while not s.is_empty():
        output.append(s.pop())

    return "".join(output)
Esempio n. 25
0
    def test_stack(self):
        stack = Stack()
        self.assertEqual(stack.is_empty(), True)
        self.assertEqual(stack.peek(), None)
        self.assertEqual(stack._head, None)

        stack.add_item("first_item")
        self.assertEqual(stack.peek(), "first_item")

        stack.add_item("second_item")
        self.assertEqual(stack.peek(), "second_item")

        stack.remove_item()
        self.assertEqual(stack.peek(), "first_item")

        stack.remove_item()
        self.assertEqual(stack.is_empty(), True)
        self.assertEqual(stack.peek(), None)
        self.assertEqual(stack._head, None)
Esempio n. 26
0
    def test_stack(self):
        s = Stack()
        self.assertEqual(True, s.is_empty())
        self.assertEqual(0, s.size())

        s.push(1)
        self.assertEqual(False, s.is_empty())
        self.assertEqual(1, s.size())

        s.push(True)
        s.push('Hello,World')
        self.assertEqual(3, s.size())

        self.assertEqual('Hello,World', s.pop())
        self.assertEqual(True, s.pop())

        s.pop()
        self.assertEqual(True, s.is_empty())
Esempio n. 27
0
 def __init__(self):
     self._stack_inp = Stack()  # для того чтобы складывать элементы
     self._stack_out = Stack()  # для извлечения элементов
     self.size = 0
Esempio n. 28
0
def infix_to_preifx(expr):
    """
    convert infix to prefix

    Args:
        expr: an infix expression in the form of '1 * ( 2 + 3 )'.

    Returns:
        An prefix expression.
    """
    # precedence dict
    prec = {"^": 4, "*": 3, "/": 3, "+": 2, "-": 2, ")": 1}

    stack = Stack()
    tokens = expr.split()

    prefix_expr = deque()
    # scan from right to left
    for token in reversed(tokens):
        # Find a right parenthesis
        if token == ')':
            stack.push(token)
        # Find a left parenthesis
        elif token == '(':
            top_token = stack.pop()
            while top_token != ')':
                prefix_expr.appendleft(top_token)
                top_token = stack.pop()
        # Find an operator
        elif token in prec:
            while not stack.isEmpty() and prec[stack.peek()] >= prec[token]:
                prefix_expr.appendleft(stack.pop())
            stack.push(token)
        # Find an operand
        else:
            prefix_expr.appendleft(token)

    while not stack.isEmpty():
        prefix_expr.appendleft(stack.pop())
    return " ".join(prefix_expr)
Esempio n. 29
0
    def test_stack(self):
        s = Stack()
        self.assertEqual(True, s.is_empty())
        self.assertEqual(0, s.size())

        s.push(1)
        self.assertEqual(False, s.is_empty())
        self.assertEqual(1, s.size())

        s.push(True)
        s.push('Hello,World')
        self.assertEqual(3, s.size())

        self.assertEqual('Hello,World', s.pop())
        self.assertEqual(True, s.pop())

        s.pop()
        self.assertEqual(True, s.is_empty())
Esempio n. 30
0
def infix_to_preifx(expr):
    """
    convert infix to prefix

    Args:
        expr: an infix expression in the form of '1 * ( 2 + 3 )'.

    Returns:
        An prefix expression.
    """
    # precedence dict
    prec = {
        "^": 4,
        "*": 3,
        "/": 3,
        "+": 2,
        "-": 2,
        ")": 1
    }

    stack = Stack()
    tokens = expr.split()

    prefix_expr = deque()
    # scan from right to left
    for token in reversed(tokens):
        # Find a right parenthesis
        if token == ')':
            stack.push(token)
        # Find a left parenthesis
        elif token == '(':
            top_token = stack.pop()
            while top_token != ')':
                prefix_expr.appendleft(top_token)
                top_token = stack.pop()
        # Find an operator
        elif token in prec:
            while not stack.isEmpty() and prec[stack.peek()] >= prec[token]:
                prefix_expr.appendleft(stack.pop())
            stack.push(token)
        # Find an operand
        else:
            prefix_expr.appendleft(token)

    while not stack.isEmpty():
        prefix_expr.appendleft(stack.pop())
    return " ".join(prefix_expr)
Esempio n. 31
0
 def setUp(self):
     self.stack = Stack()
Esempio n. 32
0
import pathmagic  # noqa
from data_structure.stack import Stack


def insert(stack, last):
    if stack.size() == 0 or stack.top() <= last:
        stack.push(last)
        return
    end = stack.pop()
    insert(stack, last)
    stack.push(end)


def sort_stack(stack):
    if stack.size() == 1:
        return
    last = stack.pop()
    sort_stack(stack)
    insert(stack, last)


if __name__ == "__main__":
    stack = Stack()
    arr = [52, 0, -63, 4, 0, 99, 4, -514651651, 651465165162, 556, -5654]
    for num in arr:
        stack.push(num)
    sort_stack(stack)
    stack.show()
Esempio n. 33
0
def generate_randomized_stack(value_range=9, stack_size=10):
    stack = Stack()
    for i in range(stack_size):
        random_int = random.randint(0, value_range)
        stack.push(random_int)
    return stack
Esempio n. 34
0
def main():
    stack = Stack()
    stack.push_all([2, 6, 1, 87, 2, 33])
    new_stack = sort_stack2(stack)
    print(new_stack)
Esempio n. 35
0
def infix_to_postifx(expr):
    """
    convert infix to postfix

    Args:
        expr: an infix expression in the form of '1 * ( 2 + 3 )'.

    Returns:
        An postfix expression of the same form.
    """
    # precedence dict
    prec = {
        "^": 4,
        "*": 3,
        "/": 3,
        "+": 2,
        "-": 2,
        "(": 1
    }

    stack = Stack()
    tokens = expr.split()

    postfix_expr = []
    for token in tokens:
        # Find a left parenthesis
        if token == '(':
            stack.push(token)
        # Find a right parenthesis
        elif token == ')':
            top_token = stack.pop()
            while top_token != '(':
                postfix_expr.append(top_token)
                top_token = stack.pop()
        # Find an operator
        elif token in prec:
            while not stack.isEmpty() and prec[stack.peek()] >= prec[token]:
                postfix_expr.append(stack.pop())
            stack.push(token)
        # Find an operand
        else:
            postfix_expr.append(token)

    while not stack.isEmpty():
        postfix_expr.append(stack.pop())
    return " ".join(postfix_expr)
Esempio n. 36
0
def sort_stack(stack):
    if stack.is_empty():
        return stack
    new_stack = Stack()
    while not stack.is_empty():
        cur = stack.pop()
        if new_stack.is_empty():
            new_stack.push(cur)
        else:
            if cur <= new_stack.peek():
                new_stack.push(cur)
            else:
                while cur > new_stack.peek():
                    stack.push(new_stack.pop())
                    if new_stack.is_empty():
                        new_stack.push(cur)
                        break
                else:
                    new_stack.push(cur)
    return new_stack
def get_max_area(height, max_area):
    stack = Stack()
    lenght = len(height)
    j = 0
    for index, data in enumerate(height):

        while(not stack.is_empty()) and height[stack.peek()] >= data:
            j = stack.pop()
            k = -1 if stack.is_empty() else stack.peek()
            max_area = max((index-k-1)*height[j], max_area)
        stack.push(index)
    while not stack.is_empty():
        j = stack.pop()
        k = -1 if stack.is_empty() else stack.peek()
        max_area = max((lenght-k-1)*height[j], max_area)
    max_area = max(lenght*height[j], max_area)
    return max_area
Esempio n. 38
0
def hanoi_problem(num, left, mid, right):
    """
    处理汉诺塔问题
    :param num: 汉诺塔最大层数
    :param left:
    :param mid:
    :param right:
    :return:
    """
    ls = Stack()
    ms = Stack()
    rs = Stack()
    ls.push(sys.maxsize)
    ms.push(sys.maxsize)
    rs.push(sys.maxsize)
    for i in reversed(range(1, num + 1)):
        ls.push(i)

    record = [Action.No]
    step = 0
    while rs.size() != num + 1:
        step += fStackTotStack(record, Action.MToL, Action.LToM, ls, ms, left,
                               mid)
        step += fStackTotStack(record, Action.LToM, Action.MToL, ms, ls, mid,
                               left)
        step += fStackTotStack(record, Action.RToM, Action.MToR, ms, rs, mid,
                               right)
        step += fStackTotStack(record, Action.MToR, Action.RToM, rs, ms, right,
                               mid)

    # print(ls)
    # print(ms)
    # print(rs)
    return step