Пример #1
0
 def _is_palindrome(self, word):
     stack1 = ArrayStack(word)
     stack2 = ArrayStack(word[::-1])
     for i in range(len(word)):
         if stack1.pop() != stack2.pop():
             return False
     return True
Пример #2
0
 def _balance(self):
     n = self.size()
     mid = n // 2
     if 3 * self.front.size() < self.back.size(
     ) or 3 * self.back.size() < self.front.size():
         f = ArrayStack()
         for i in range(mid):
             f.add(i, self.get(mid - i - 1))
         b = ArrayStack()
         for i in range(n - mid):
             b.add(i, self.get(mid + i))
         self.front = f
         self.back = b
Пример #3
0
def queue_to_stack(queue):
    """
    Convert queue to stack
    """
    stack1 = ArrayStack()
    stack2 = ArrayStack()
    while len(queue) != 0:
        num = queue.pop()
        stack1.push(num)
    while len(stack1) != 0:
        num = stack1.pop()
        stack2.push(num)
    return stack2
def queue_to_stack(queue):
    '''
    Conver queue to stack.
    '''
    queue_copy = deepcopy(queue)
    stack = ArrayStack()
    while queue_copy:
        stack.push(queue_copy.pop())

    result = ArrayStack()
    while stack:
        result.push(stack.pop())
    return result
def queue_to_stack(queue):
    """Converts queue to a stack"""
    output_stack = ArrayStack()
    start_queue = copy.deepcopy(queue)
    temporary_stack = ArrayStack()

    while start_queue.isEmpty() is False:
        elem = start_queue.pop()
        temporary_stack.push(elem)

    while temporary_stack.isEmpty() is False:
        elem = temporary_stack.pop()
        output_stack.push(elem)

    return output_stack
Пример #6
0
def isPalindrome(string):
    """Returns True if string is a palindrome
    or False otherwise."""
    stack1 = ArrayStack()
    stack2 = ArrayStack()

    for rep in range(0, len(string) - 1):
        stack1.push(string[rep])
    for rep in range(len(string) - 1, 0, -1):
        stack2.push(string[rep])

    if stack1 == stack2:
        return True
    else:
        return False
Пример #7
0
def getOut(row, column, maze):
    """(row,column) is the position of the start symbol in the maze.
    Returns True if the maze can be solved or False otherwise."""
    # States are tuples of coordinates of cells in the grid.
    stack = ArrayStack()
    stack.push((row, column))
    while not stack.isEmpty():
        (row, column) = stack.pop()
        if  maze[row][column] == 'T': 
            return True
        elif maze[row][column] != '.':
            # Cell has not been visited, so mark it and push adjacent unvisited
            # positions onto the stack
            maze[row][column] = '.'
            # Try NORTH
            if row != 0 and not maze[row - 1][column] in ('*', '.'):
                stack.push((row - 1, column))             
            # Try SOUTH
            if row + 1 != maze.getHeight() and not maze[row + 1][column] in ('*', '.'):         
                stack.push((row + 1, column))             
            # Try EAST
            if column + 1 != maze.getWidth() and not maze[row][column + 1] in ('*', '.'):         
                stack.push((row, column + 1))             
            # Try WEST
            if column != 0 and not maze[row][column - 1] in ('*', '.'):         
                stack.push((row, column - 1))
    return False
 def test_arraystack_popallthrowsempty(self):
     stack = ArrayStack()
     for i in range(100):
         stack.push(i + 1)
     for i in range(100):
         stack.pop()
     stack.pop()
Пример #9
0
    def find_palindromes(self, input_file, output_file):
        '''
        Find palindromes using stack
        '''
        palindroms = []

        self.input_file = input_file
        self.output_file = output_file

        words = self.read_file(self.input_file)

        for word in words:
            word_lst = list(word)
            word_stack = ArrayStack()

            flag = True

            for letter in range(len(word_lst)-1, -1, -1):
                word_stack.push(word[letter])

            while not word_stack.isEmpty():
                if word_stack.pop() != word_lst.pop():
                    flag = False
                    break

            if flag:
                palindroms.append("".join(word))

        self.write_to_file(self.output_file, palindroms)
        return palindroms
Пример #10
0
 def convert(self):
     """Returns a list of tokens that represent the postfix
     form.  Assumes that the infix expression is syntactically correct"""
     postfix = []
     stack = ArrayStack()
     while self._scanner.hasNext():
         currentToken = self._scanner.next()
         if currentToken.getType() == Token.INT:
             postfix.append(currentToken)
         elif currentToken.getType() == Token.LPAR:
             stack.push(currentToken)
         elif currentToken.getType() == Token.RPAR:
             topOperator = stack.pop()
             while topOperator.getType() != Token.LPAR:
                 postfix.append(topOperator)
                 topOperator = stack.pop()
         else:
             while not stack.isEmpty() and \
                   currentToken.getType() != Token.EXPO and \
                   stack.peek().getPrecedence() >= currentToken.getPrecedence():
                 postfix.append(stack.pop())
             stack.push(currentToken)
     while not stack.isEmpty():
         postfix.append(stack.pop())
     return postfix
Пример #11
0
    def convert(self):
        postfix = [] #Creating an empty list to store the postfix expression
        storage = ArrayStack() #Creates a stack to store the operands when converting the expression.
        while self._infix.hasNext():
            current = self._infix.next()
            if current.getType() == Token.INT:
                postfix.append(current)
            elif current.getType() == Token.LeftPar:
                storage.push(current)
                self._operand += 1
            elif current.getType() == Token.RightPar:
                self._operator += 1
                topOpInSt = storage.pop()
                while topOpInSt.getType() != Token.LeftPar:
                    postfix.append(topOpInSt)
                    topOpInSt = storage.pop()
            elif current.getType() == Token.LeftBrac:
                storage.push(current)
                self._operand += 1
            elif current.getType() == Token.RightBrac:
                self._operator += 1
                a = storage.pop()
                while a.getType() != Token.LeftBrac:
                    postfix.append(a)
                    a = storage.pop()
            else:
		#The loop below tells the program to go through the array that is created so far, and as long as it is not empty and the precedence found in the Tokens.py file of the first item in the array is greater than or equal to the precedence of the current token the Scanner is on, the program continues.
                while not storage.isEmpty() and storage.peek().getPrecedence() >= current.getPrecedence():
                    postfix.append(storage.pop())
                storage.push(current)
        if self._operand > self._operator or self._operator > self._operator:
            return "Unbalanced Expression"
        while not storage.isEmpty():
            postfix.append(storage.pop())
        return postfix
Пример #12
0
 def arremstor_unit_test(self):
     temp = ArrayStack()
     for count in range(20):
           temp.push(count+1)
     for count in range(15):
           temp.pop()
     self.assertEqual(len(temp.items), 10)
Пример #13
0
def is_matched_html(raw):
    """Return True if all HTML tags are properly matched;
    False Otherwise."""
    S = ArrayStack()
    # find first '<' character
    start = raw.find('<')
    while start != -1:
        # find next '>' character
        end = raw.find('>', start + 1)
        if end == -1:
            return False
        # strip away < >
        tag = raw[start + 1:end]
        # this is opening tag
        if not tag.startswith('/'):
            S.push(tag)
        # this is closing tag
        else:
            if S.is_empty():
                return False
            if tag[1:] != S.pop():
                return False
        start = raw.find('<', end + 1)
    # all tags matched
    return S.is_empty()
Пример #14
0
def queue_to_stack(queue):
    """
    Converts queue to stack.
    """
    temp_queue = ArrayQueue()
    temp_stack = ArrayStack()  #elements are in reversed order
    result_stack = ArrayStack()
    while not queue.isEmpty():
        elem = queue.pop()
        temp_queue.add(elem)
        temp_stack.push(elem)
    while not temp_queue.isEmpty():
        queue.add(temp_queue.pop())
    while not temp_stack.isEmpty():
        result_stack.push(temp_stack.pop())  #we reverse elements
    return result_stack
Пример #15
0
def getOut(row, column, maze):
    """(row,column) is the position of the start symbol in the maze.
    Returns True if the maze can be solved or False otherwise."""
    # States are tuples of coordinates of cells in the grid.
    stack = ArrayStack()
    stack.push((row,column))
    while not stack.isEmpty():
        if maze[row][column] == 'T':
            return True
        else:
            # Try NORTH
            if row != 0 and not maze[row - 1][column] in ('*', '.'):
                stack.push((row - 1, column))
                maze[row-1][column] = '.'
            # Try SOUTH
            elif row != maze.getHeight() and not maze[row + 1][column] in('*','.'):
                stack.push((row + 1, column))
                maze[row+1][column] = '.'
            # Try EAST
            elif column != maze.getWidth() and not maze[row][column + 1] in('*','.'):
                stack.push((row,column + 1))
                maze[row][column + 1] = '.'
            # Try WEST
            elif column != 0 and not maze[row][column - 1] in ('*','.'):
                stack.push((row,column - 1))
                maze[row][column - 1] = '.'
            
    return False
Пример #16
0
    def find_palindromes(self, read_from: str, write_to: str) -> list:
        """
        Finds all palindromes from the file and
        write it into another one
        Returns a list with palindromes
        """
        words = self.read_file(read_from)
        palindromes = list()
        stack_with_words = ArrayStack()
        reversed_word = ""

        for word in words:
            for char in word:
                stack_with_words.push(char)

            while not stack_with_words.isEmpty():
                reversed_word += stack_with_words.pop()

            if reversed_word == word:
                palindromes.append(word)

            reversed_word = ""

        self.write_in_file(write_to, palindromes)

        return palindromes
Пример #17
0
 def find_palindromes(self, file, file_name):
     """
     method which finds palindroms.
     """
     words_list = self.read_file(file)
     stack = ArrayStack()
     result = []
     for word in words_list:
         word_len = len(word)
         if word_len == 1.0:
             result.append(word)
         else:
             word_mid = word_len // 2
             middle = word_len % 2
             for i in range(word_len):
                 if i < word_mid:
                     stack.push(word[i])
                 elif middle == 1 and i == word_mid:
                     continue
                 else:
                     if stack.pop() != word[i]:
                         check = False
                         break
                     check = True
             if check is True:
                 result.append(word)
     self.write_to_file(result, file_name)
     return result
Пример #18
0
 def lipop_unit_test(self):
     temp = ArrayStack()
     for count in range(4):
           temp.push(count+1)
     temp.pop()
     self.assertEqual(temp.peek(), 3)
     temp.pop()
     self.assertEqual(len(temp),2)
Пример #19
0
def queue_to_stack(queue):
    copied = copy(queue)
    future_stack = []
    while True:
        try:
            future_stack.append(copied.pop())
        except KeyError:
            return ArrayStack(reversed(future_stack))
Пример #20
0
    def is_palindrome(self, word):
        """
        Checks whether the word is a palindrome.
        """
        if len(word) <= 1:
            return False
        mid = len(word)/2
        if mid == int(mid):
            stack1, str2 = ArrayStack(word[:int(mid)]), word[int(mid):]
        else:
            stack1, str2 = ArrayStack(word[:int(mid)]), word[int(mid)+1:]
        # print(f"WORD: {word}\nFIRST PART: {str(stack1)}\nSECOND PART: {str2}")

        for char in str2:
            if stack1.pop() != char:
                return False
        # print("FOUND PALINDROME:", word)
        return True
Пример #21
0
def test_stack():
    S = ArrayStack()
    S.push(5)
    print(S.top())
    S.push(6)
    print(len(S))
    print(S.pop())
    print(S.is_empty())
    print(S.data)
def queueToStack(queue):
    queue_copy = copy.deepcopy(queue)
    stack = ArrayStack()
    while True:
        try:
            stack.add(queue_copy.pop())
        except KeyError:
            break
    return stack
Пример #23
0
def queue_to_stack(queue):
    '''Convert queue to stack, without modifying the queue
    peek of the stack must be first element of the queue'''
    stack = ArrayStack()
    queue_copy = ArrayQueue(queue)

    while len(queue_copy) != 0:
        stack.push(queue_copy.remove(len(queue_copy) - 1))

    return stack
Пример #24
0
def isPalindrome(string):
    """Returns True if string is a palindrome
    or False otherwise."""
    stk = ArrayStack()
    for ch in string:
        stk.push(ch)
    for ch in string:
        if ch != stk.pop():
            return False
    return True
Пример #25
0
def stack_to_queue(stack):
    '''Convert stack to queue, without changing given stack
    peek of the stack is the first element in the queue'''
    queue = ArrayQueue()
    stack_copy = ArrayStack(stack)

    while len(stack_copy) != 0:
        queue.add(stack_copy.pop())

    return queue
Пример #26
0
def queue_to_stack(queue):
    """
    converts queue to a stack
    """
    queue_copy = ArrayQueue(queue)
    stack = ArrayStack()
    while True:
        try:
            element = queue_copy.pop()
            stack.push(element)
        except KeyError:
            break
    stack_reversed = ArrayStack()
    while True:
        try:
            element = stack.pop()
            stack_reversed.push(element)
        except KeyError:
            break
    return stack_reversed
Пример #27
0
def queue_to_stack(queue):
    """
    Converts queue to stack.
    """
    list_queue = []
    for i in queue.__iter__():
        list_queue.append(i)
    list_stack = list_queue[::-1]
    new_stack = ArrayStack()
    for j in range(len(list_queue)):
        new_stack.push(list_stack[j])
    return new_stack
Пример #28
0
def queue_to_stack(queue: ArrayQueue) -> ArrayStack:
    """
    Converts queue to stack and returns Stack object
    """
    stack = ArrayStack()
    copy_of_queue = deepcopy(queue)

    for ind in range(len(queue), 0, -1):
        ind -= 1
        stack.add(copy_of_queue.remove(ind))

    return stack
Пример #29
0
def queue_to_stack(queue):
    """
    Convert a queue to a stack using another stack
    """
    input_queue = copy.deepcopy(queue)
    output_stack = ArrayStack()
    converter_stack = ArrayStack()
    # Get the queue items
    while True:
        try:
            converter_stack.push(input_queue.pop())
        except KeyError:
            break
    # Reverse the queue
    while True:
        try:
            output_stack.push(converter_stack.pop())
        except KeyError:
            break

    return output_stack
Пример #30
0
 def check_palindrome(s):
     s = str(s)
     stack = ArrayStack()
     even = 1 if len(s) % 2 else 0
     half = len(s) // 2
     for i in range(half):
         stack.push(s[i])
     ind = half + even
     for i in range(half):
         if stack.pop() != s[ind + i]:
             return False
     return True