def has_word(current):
        index, stack = 0, Stack()
        stack.push(current)

        while not stack.is_empty():
            current = stack.pop()

            if current[0] == 'PARENT_MARKER':
                visited.remove(current[1])
                index -= 1
                continue

            if board[current[0]][current[1]] is not word[index]:
                continue

            if index + 1 == length:
                return True

            visited.add(current)
            index += 1

            # Mark the parent of the below children so that if all children are processed and no word is found,
            # we can remove the parent from visited as well and move onto the remaining items in the stack
            stack.push(('PARENT_MARKER', current))

            for next in neighbors(current, n, m):
                if next in visited:
                    continue

                stack.push(next)

        return False
def postfix_eval(postfix_expr):
    operand_stack = Stack()
    token_list = postfix_expr.split()

    for token in token_list:
        if token in "0123456789":
            operand_stack.push(int(token))
        else:
            operand2 = operand_stack.pop()
            operand1 = operand_stack.pop()
            result = do_math(token, operand1, operand2)
            operand_stack.push(result)
    return operand_stack.pop()
def sort_stack(stack):
    if stack.size() == 0:
        return stack
    temp_stack = Stack.new()
    while not stack.is_empty():
        element = stack.pop()
        while not temp_stack.is_empty() and temp_stack.peek() > element:
            temp_stack_element = temp_stack.pop()
            stack.push(temp_stack_element)
        temp_stack.push(element)
    return temp_stack
def depth_first_search(root, isItem):
    s = Stack()
    s.push(root)
    while not s.is_empty():
        node = s.pop()
        if isItem(node['val']):
            return True
        try:
            for child in node['children']:
                s.push(child)
        except KeyError:
            continue
    return False
def evaluate(string):
    stack = Stack()  # Stack<string>
    for char in string:
        if char in OPERATIONS or char == '(':
            stack.push(char)
        if char == ')':
            digit = stack.pop()
            stack.pop()  # remove the open parenthesis
            handleDigit(stack, digit)
        if char.isdigit():
            handleDigit(stack, char)

        # ignore other characters

    return int(stack.pop())
示例#6
0
def reverse_list(arr):
    stack = Stack()
    reversed = []
    for item in arr:
        stack.push(item)
    while stack.size() > 0:
        reversed.append(stack.pop())
    return reversed
示例#7
0
def cannot_be_valid(expr):
    close = Stack()

    for char in reversed(expr):
        if char == CLOSE:
            close.push(char)
            continue

        try:
            close.pop()
        # an opening paren was reached with no closing tags to the right of it, this _could_ be valid
        except IndexError:
            return False

    return not close.is_empty()
def is_palindrome(list):
    if not list.head():
        return True  # Empty lists are empty strings, and as such they are palindromes.
    fast_runner = list.head()
    slow_runner = list.head()
    reversed_half = Stack.new()
    i = 0
    # Position slow runner in the middle of the linked list.
    while fast_runner is not None:
        fast_runner = fast_runner.next_element()
        i += 1
        if i % 2 == 0:
            reversed_half.push(slow_runner)
            slow_runner = slow_runner.next_element()
    if i % 2 != 0:  # Edge case for odd length linked lists.
        reversed_half.push(slow_runner)
    while slow_runner is not None:
        elem = reversed_half.pop()
        if slow_runner.data() != elem.data():
            return False
        slow_runner = slow_runner.next_element()
    return True
def par_checker(symbol_string):
    s = Stack()
    balanced = True
    index = 0

    while index < len(symbol_string) and balanced:
        symbol = symbol_string[index]
        if symbol in "([{":
            s.push(symbol)
        else:
            if s.is_empty():
                balanced = False
            else:
                top = s.pop()
                if not matches(top, symbol):
                    balanced = False

        index = index + 1

    if balanced and s.is_empty():
        return True
    else:
        return False
 def __init__(self, size_limit):
     if size_limit <= 0:
         raise ValueError("Stack size limit needs to be positive.")
     self._size_limit = size_limit
     self._stack = Stack.new()
 def __init__(self):
     self._enqueue = Stack()
     self._dequeue = Stack()
class Queue:
    def __init__(self):
        self._enqueue = Stack()
        self._dequeue = Stack()

    def is_empty(self):
        return self._enqueue.is_empty() and self._dequeue.is_empty()

    def size(self):
        return self._dequeue.size() + self._enqueue.size()

    def enqueue(self, item):
        self._enqueue.push(item)

    def dequeue(self):
        if self._dequeue.is_empty():
            while not self._enqueue.is_empty():
                self._dequeue.push(self._enqueue.pop())
        return self._dequeue.pop()

    def stdout(self):
        print('_enqueue')
        self._enqueue.stdout()
        print('_dequeue')
        self._dequeue.stdout()
示例#13
0
 def __init__(self):
     self._newest_elements = Stack.new()
     self._oldest_elements = Stack.new()
示例#14
0
 def __init__(self, index):
     self._disks = Stack.new()
     self._index = index
示例#15
0
 def __init__(self, limit=10):
     self.limit = limit
     self.stack_one = Stack(limit)
     self.stack_two = Stack(limit)
def infix_to_postfix(infix_expr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    op_stack = Stack()
    postfix_list = []
    token_list = infix_expr.split()

    for token in token_list:
        if token in "ABCDEFGHIJKLMNOPQRSTUWXYZ" or token in "0123456789":
            postfix_list.append(token)
        elif token == '(':
            op_stack.push(token)
        elif token == ')':
            top_token = op_stack.pop()

            while top_token != '(':
                postfix_list.append(top_token)
                top_token = op_stack.pop()

        else:
            while (not op_stack.is_empty()) and \
                    (prec[op_stack.peek()] >= prec[token]):
                postfix_list.append(op_stack.pop())
            op_stack.push(token)

    while not op_stack.is_empty():
        postfix_list.append(op_stack.pop())

    return " ".join(postfix_list)
示例#17
0
class StackQueue:
    """
    Implementation of Queue using two Stacks.
    """
    def __init__(self, limit=10):
        self.limit = limit
        self.stack_one = Stack(limit)
        self.stack_two = Stack(limit)

    def enqueue(self, item):
        if self.isFull():
            raise QueueOverflowError("Cannot insert item in a full queue.")
        self.stack_one.push(item)

    def _move_item_to_second_stack(self):
        if self.stack_two.is_empty():
            while not self.stack_one.is_empty():
                self.stack_two.push(self.stack_one.pop())

    def dequeue(self):
        if self.isEmpty():
            raise QueueUnderflowError(
                "Cannot Remove an item from empty Queue.")
        self._move_item_to_second_stack()
        return self.stack_two.pop()

    def peek(self):
        self._move_item_to_second_stack()
        return self.stack_two.peek()

    def isEmpty(self):
        return self.stack_one.is_empty() and self.stack_two.is_empty()

    def isFull(self):
        return (self.stack_one.size() + self.stack_two.size()) >= self.limit
示例#18
0
"""

from stacks.stack import Stack


def to_str(n, base):
    convert_string = "0123456789ABCDEF"
    print(convert_string[int(n % base)])
    print("n: ", n, "base: ", base)
    if n < base:
        return convert_string[int(n)]
    else:
        return to_str(n / base, base) + convert_string[int(n % base)]


r_stack = Stack()


def to_str_with_stack(n, base):
    convert_string = "0123456789ABCDEF"
    while n > 0:
        if n < base:
            r_stack.push(convert_string[n])
        else:
            r_stack.push(convert_string[n % base])
        n = n // base
    res = ""
    while not r_stack.is_empty():
        res = res + str(r_stack.pop())
    return res