Beispiel #1
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
def queueToStack(queue):
    queue_copy = copy.deepcopy(queue)
    stack = ArrayStack()
    while True:
        try:
            stack.add(queue_copy.pop())
        except KeyError:
            break
    return stack
Beispiel #3
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
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
Beispiel #5
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
Beispiel #6
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)
Beispiel #7
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
Beispiel #8
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
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
Beispiel #10
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 stack_to_queue(stack):
    """
    Return queue from stack (front of queue is peek of stack).
    """
    copy_stack = ArrayStack()
    queue = ArrayQueue()
    for element in stack:
        copy_stack.push(element)

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

    return queue
def queue_to_stack(queue):
    """
    Converts the queue to a stack.
    """
    stk_ar = ArrayStack()
    q = ArrayQueue(queue)
    el = []
    while not q.isEmpty():
        el.append(q.pop())
    q1 = ArrayQueue(el[::-1])
    while not q1.isEmpty():
        stk_ar.push(q1.pop())
    return stk_ar
 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()
Beispiel #14
0
def queue_to_stack(queue: ArrayQueue) -> ArrayStack:
    """
    Return stack from queue (front of queue is peek of stack).
    """

    copy_queue = ArrayQueue()
    stack = ArrayStack()
    for element in queue:
        copy_queue.add(element)

    reversed_queue = reverse_queue(copy_queue)
    for element in reversed_queue:
        stack.push(element)

    return stack
Beispiel #15
0
    def find_palindromes(self, read_filename: str,
                         write_filename: str) -> list:
        """
        Return list of polindromes.
        """

        self.read_file(read_filename)
        words = self._stack
        polindromes = ArrayStack()
        for word in words:
            if word == word[-1::-1]:
                polindromes.push(word)

        self.write_to_file(write_filename, polindromes)
        return list(polindromes)
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
Beispiel #17
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
Beispiel #18
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
Beispiel #20
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))
def checkBalance(st):
    stck = ArrayStack()
    for i in st:
        if i == '[' or i == '{' or i == '(':
            stck.push(i)
        else:
            if i == ']' or i == '}' or i == ')':
                if stck.isEmpty() or stck.peek() != opposite(i):
                    return False
                else:
                    stck.pop()
    if stck.isEmpty():
        return True
    return False
Beispiel #22
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()
Beispiel #23
0
class PFEvaluator(object):
   
    def __init__(self, scanner):
        self._expressionSoFar = ""
        self._operandStack = ArrayStack()
        self._scanner = scanner

    def evaluate(self):
        while self._scanner.hasNext():
            currentToken = self._scanner.next()
            self._expressionSoFar += str(currentToken) + " "
            if currentToken.getType() == Token.INT:
                self._operandStack.push(currentToken)
            elif currentToken.isOperator(): 
                if len(self._operandStack) < 2:
                    raise Exception("Too few operands on the stack")
                t2 = self._operandStack.pop()
                t1 = self._operandStack.pop()
                result = Token(self._computeValue(currentToken,
                                                  t1.getValue(),
                                                  t2.getValue()))
                self._operandStack.push(result)

            else:
                raise Exception("Unknown token type")
        if len(self._operandStack) > 1:
            raise Exception("Too many operands on the stack")
        result = self._operandStack.pop()
        return result.getValue();   

    def __str__(self):
        result = "\n"
        if self._expressionSoFar == "":
            result += "Portion of expression processed: none\n"
        else: 
            result += "Portion of expression processed: " + \
                   self._expressionSoFar + "\n"
        if self._operandStack.isEmpty():
            result += "The stack is empty"
        else:
            result += "Operands on the stack          : " + \
                      str(self._operandStack)
        return result

    def _computeValue(self, op, value1, value2):
        result = 0;
        theType = op.getType()
        if theType == Token.PLUS:
            result = value1 + value2;
        elif theType == Token.MINUS:
            result = value1 - value2;
        elif theType == Token.MUL:
            result = value1 * value2;
        elif theType == Token.DIV:
            result = value1 // value2;
        elif theType == Token.EXP:
            result = value1 ** value2;
        else:
            raise Exception("Unknown operator")
        return result
Beispiel #24
0
class PFEvaluator(object):
    def __init__(self, scanner):
        self._expression_so_far = ""
        self._operand_stack = ArrayStack()
        self._scanner = scanner

    def evaluate(self):
        while self._scanner.has_next():
            current_token = self._scanner.next()
            self._expression_so_far += str(current_token) + " "
            if current_token.get_type() == Token.INT:  # 数字入栈
                self._operand_stack.push(current_token)
            elif current_token.is_operator():  # 操作符计算
                if len(self._operand_stack) < 2:  # 栈内数字小于2
                    raise AttributeError (\
                        "Too few operands on the stack")
                t2 = self._operand_stack.pop()
                t1 = self._operand_stack.pop()
                result = \
                        Token(self._compute_value(current_token,
                                                    t1.get_value(),
                                                    t2.get_value()))
                self._operand_stack.push(result)
            else:
                raise AttributeError("Unknown token type")
        if len(self._operand_stack) > 1:  # 计算完成后, 栈内深入数字大于2
            raise AttributeError(\
                "Too many operands on the stack")
        result = self._operand_stack.pop()
        return result.get_value()

    def __str__(self):
        result = "\n"
        if self._expression_so_far == "":
            result += \
                "Portion of expression processed none\n"
        else:
            result += "Portion of expression processed: " + \
                self._expression_so_far + "\n"
        if self._operand_stack.isEmpty():
            result += "Thre stack is empty"
        else:
            result += "Operands on the stack: " + \
                str(self._operand_stack)
        return result

    def _compute_value(self, op, value1, value2):
        result = 0
        the_type = op.get_type()
        if the_type == Token.PLUS:
            result = value1 + value2
        elif the_type == Token.MINUS:
            result = value1 - value2
        elif the_type == Token.MUL:
            result = value1 * value2
        elif the_type == Token.DIV:
            result = value1 // value2
        else:
            raise AttributeError("Unknown operator")
        return result
Beispiel #25
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
 def find_palindromes(self, path: str, wirte_file: str) -> list:
     """
     Return list of palindormes and writes them to file.
     """
     palindromes = []
     all_words = self.read_file(path)
     for word in all_words:
         palindrome = True
         word_stack = ArrayStack()
         for letter in word[:len(word) // 2]:
             word_stack.push(letter)
         for letter in word[(len(word) + 1) // 2:]:
             if letter != word_stack.pop():
                 palindrome = False
         if palindrome:
             palindromes.append(word)
     self.write_to_file(palindromes, wirte_file)
     return palindromes
Beispiel #27
0
    def find_palindromes(self, file_to_read, file_to_write):
        """
        Finds palindromes in a file and writes them to another file.
        """
        self.palindomes = []
        new_stack = ArrayStack()
        list_of_words = self.read_file(file_to_read)
        self.file_to_write = file_to_write

        for word in list_of_words:
            for letter in word:
                new_stack.push(letter)
            try:
                if self.check(word, new_stack):
                    self.palindomes.append(word)
                    self.write_to_file(word)
            except KeyError:
                continue
        return self.palindomes
Beispiel #28
0
class PFEvaluator(object):
   
    def __init__(self, scanner):
        self._expressionSoFar = ""
        self._operandStack = ArrayStack()
        self._scanner = scanner

    def evaluate(self):
        while self._scanner.hasNext():
            currentToken = self._scanner.next()
            self._expressionSoFar += str(currentToken) + " "
            if currentToken.getType() == Token.INT:
                self._operandStack.push(currentToken)
            elif currentToken.isOperator(): 
                if len(self._operandStack) < 2:
                    raise AttributeError("Too few operands on the stack")
                t2 = self._operandStack.pop()
                t1 = self._operandStack.pop()
                result = Token(self._computeValue(currentToken,
                                                  t1.getValue(),
                                                  t2.getValue()))
                self._operandStack.push(result)

            else:
                raise AttributeError("Unknown token type")
        if len(self._operandStack) > 1:
            raise AttributeError("Too many operands on the stack")
        result = self._operandStack.pop()
        return result.getValue();   

    def __str__(self):
        result = "\n"
        if self._expressionSoFar == "":
            result += "Portion of expression processed: none\n"
        else: 
            result += "Portion of expression processed: " + \
                   self._expressionSoFar + "\n"
        if self._operandStack.isEmpty():
            result += "The stack is empty"
        else:
            result += "Operands on the stack          : " + \
                      str(self._operandStack)
        return result

    def _computeValue(self, op, value1, value2):
        result = 0;
        theType = op.getType()
        if theType == Token.PLUS:
            result = value1 + value2;
        elif theType == Token.MINUS:
            result = value1 - value2;
        elif theType == Token.MUL:
            result = value1 * value2;
        elif theType == Token.DIV:
            result = value1 // value2;
        else:
            raise Exception("Unknown operator")
        return result
Beispiel #29
0
 def find_palindromes(self, file_from, file_to):
     """
     fincs all the palindromes and writes them to file_to
     """
     self.read_file(file_from)
     palindromes = ArrayStack()
     for word in self.words:
         if self.is_palindrome(word):
             palindromes.push(word)
     self.palindromes = []
     while True:
         try:
             word = palindromes.pop()
             # if len(word) > 1: -- would've been useful for end version
             self.palindromes.append(word)
         except KeyError:
             break
     self.palindromes = self.palindromes[::-1]
     self.write_to_file(file_to)
     return self.palindromes
Beispiel #30
0
def check_brackets(s):
    stack = ArrayStack()
    for i in s:
        if i == "(":
            stack.push("(")
        if i == ")":
            if stack.isEmpty():
                return False
            stack.pop()
    if stack.isEmpty():
        return True
    else:
        return False
Beispiel #31
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
Beispiel #32
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
def infixToPostfix(exp):
    stck = ArrayStack()
    postfix = ""
    for i in range(len(exp)):
        if isOperand(exp[i]):
            postfix += exp[i]
        else:
            if stck.isEmpty():
                stck.push(exp[i])
            else:
                if prec(exp[i]) >= prec(stck.peek()):
                    stck.push(exp[i])
                else:
                    while not stck.isEmpty() and prec(exp[i]) < prec(stck.peek()):
                        postfix += stck.pop()
                    stck.push(exp[i])
        # print "Stack:", stck.printStack(), "Expression:", postfix
    while not stck.isEmpty():
        postfix += stck.pop()
    return postfix
Beispiel #34
0
 def __init__(self, scanner):
     self._expressionSoFar = ""
     self._operandStack = ArrayStack()
     self._scanner = scanner
Beispiel #35
0
class RootishArrayStack(BaseList):
    def __init__(self, iterable=[]):
        self._initialize()
        self.add_all(iterable)
        
    def _initialize(self):
        self.n = 0
        self.blocks = ArrayStack()

    def _i2b(self, i):
        return int(ceil((-3.0 + sqrt(9 + 8*i)) / 2.0))
    
    def grow(self):
        self.blocks.append(new_array(self.blocks.size()+1))
    
    def shrink(self):
        r = self.blocks.size()
        while r > 0 and (r-2)*(r-1)/2 >= self.n:
            self.blocks.remove(self.blocks.size()-1)
            r -= 1
    
    def get(self, i):
        if i < 0 or i > self.n - 1: raise IndexError()
        b = self._i2b(i)
        j = i - b*(b+1)/2
        return self.blocks.get(b)[j]

    def set(self, i, x):
        if i < 0 or i > self.n - 1: raise IndexError()
        b = self._i2b(i)
        j = i - b*(b+1)/2
        y = self.blocks.get(b)[j]
        self.blocks.get(b)[j] = x
        return y
    
    def add(self, i, x):
        if i < 0 or i > self.n: raise IndexError()
        r = self.blocks.size()
        if r*(r+1)/2 < self.n + 1: self.grow()
        self.n += 1
        for j in range(self.n-1, i, -1):
            self.set(j, self.get(j-1))
        self.set(i, x)
    
    def remove(self, i):
        if i < 0 or i > self.n - 1: raise IndexError()
        x = self.get(i)
        for j in range(i, self.n-1):
            self.set(j, self.get(j+1))
        self.n -= 1
        r = self.blocks.size()
        if (r-2)*(r-1)/2 >= self.n: self.shrink()
        return x

    def clear(self):
        self.blocks.clear()
        n = 0
Beispiel #36
0
 def _initialize(self):
     self.n = 0
     self.blocks = ArrayStack()
Beispiel #37
0
 def _initialize(self):
     self.front = ArrayStack()
     self.back = ArrayStack()
Beispiel #38
0
class DualArrayDeque(BaseList):
    def __init__(self, iterable=[]):
        self._initialize()
        self.add_all(iterable)

    def _initialize(self):
        self.front = ArrayStack()
        self.back = ArrayStack()

    def get(self, i):
        if i < self.front.size():
            return self.front.get(self.front.size() - i - 1)
        else:
            return self.back.get(i - self.front.size())

    def set(self, i, x):
        if i < self.front.size():
            return self.front.set(self.front.size() - i - 1, x)
        else:
            return self.back.set(i - self.front.size(), x)

    def add(self, i, x):
        if i < self.front.size():
            self.front.add(self.front.size() - i, x)
        else:
            self.back.add(i - self.front.size(), x)
        self._balance()

    def remove(self, i):
        if i < self.front.size():
            x = self.front.remove(self.front.size() - i - 1)
        else:
            x = self.back.remove(i - self.front.size())
        self._balance()
        return x

    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

    def clear(self):
        self.front.clear()
        self.back.clear()

    def size(self):
        return self.front.size() + self.back.size()
Beispiel #39
0
 def convert(self):
     operatorStack = ArrayStack() #this will hold operators and grouping symbols
     postfixExpression = "" #this will hold the final expression
     while self.scanner.hasNext():
         token_char = self.scanner.next()
         if token_char.getType() == 4: #it's an integer
             postfixExpression += str(token_char.getValue()) + " "
         elif token_char.getValue() in ['(','[']: #left parenthesis
             operatorStack.push(token_char)
         elif token_char.isOperator(): #it's an operator
             #pop off all the operators with equal or greater precedence
             while len(operatorStack) != 0 and operatorStack.peek().getPrecedence() >= token_char.getPrecedence():
                 postfixExpression += str(operatorStack.pop().getValue()) + " "
             #now we can push the new operator onto the stack
             operatorStack.push(token_char)
         elif token_char.getValue() in [')',']']: #right parenthesis
             while len(operatorStack) != 0 and operatorStack.peek().getValue() not in ['(','[']: #find the matching one
                 postfixExpression += str(operatorStack.pop().getValue()) + " "
             operatorStack.pop() #discard the left parenthesis
         elif token_char.getType() == 0 and token_char.getValue() not in ['(',')','[',']']: 
             raise Exception("Error: unknown character.") #unknown character
     #transfer over any remaining operators
     while len(operatorStack) != 0:
         postfixExpression += str(operatorStack.pop().getValue()) + " "
     return postfixExpression
Beispiel #40
0
 def in_edges(self, i):
     out = ArrayStack()
     for j in range(self.n):
         if self.has_edge(j, i): out.append(j)
     return out