Ejemplo n.º 1
0
class Translator(object):
    """Translates infix expressions to postfix expressions."""

    def __init__(self, scanner):
        """Sets the initial state of the translator."""
        self._expressionSoFar = ""
        self._operatorStack = LinkedStack()
        self._scanner = scanner


    def translate(self):
        """Returns a list of tokens that represent the postfix
        form of sourceStr.  Assumes that the infix expression
        in sourceStr is syntactically correct"""
        postfix = list()
        for currentToken in self._scanner:
            self._expressionSoFar += str(currentToken) + " "
            if currentToken.getType() == Token.INT:
                postfix.append(currentToken)
            elif currentToken.getType() == Token.LPAR:
                self._operatorStack.push(currentToken)
            elif currentToken.getType() == Token.RPAR:
                topOperator = self._operatorStack.pop()
                while topOperator.getType() != Token.LPAR:
                    postfix.append(topOperator)
                    topOperator = self._operatorStack.pop()
            else:
                while not self._operatorStack.isEmpty() and \
                      self._operatorStack.peek().getPrecedence() >= \
                      currentToken.getPrecedence():
                    postfix.append(self._operatorStack.pop())
                self._operatorStack.push(currentToken)
        while not self._operatorStack.isEmpty():
            postfix.append(self._operatorStack.pop())
        return postfix
   
    def __str__(self):
        """Returns a string containing the contents of the expression
        processed and the stack to this point."""
        result = "\n"
        if self._expressionSoFar == "":
            result += "Portion of expression processed: none\n"
        else: 
            result += "Portion of expression processed: " + \
                   self._expressionSoFar + "\n"
        if self._operatorStack.isEmpty():
            result += "The stack is empty"
        else:
            result += "Operators on the stack          : " + \
                      str(self._operatorStack)
        return result

    def translationStatus(self):
        return str(self)
Ejemplo n.º 2
0
def brackets_Checker():
    stk = LinkedStack()
    for ch in exp:
        if ch in ['[', '(']:
            stk.push(ch)
        elif ch in [']', ')']:
            if stk.isEmpty():
                return False
            chFromStack = stk.pop()
            if ch == ']' and chFromStack != '[' or ch == ')' and chFromStack != '(':
                return False
        return stk.isEmpty()
Ejemplo n.º 3
0
class Translator(object):
    """Translates infix expressions to postfix expressions."""
    def __init__(self, scanner):
        """Sets the initial state of the translator."""
        self._expressionSoFar = ""
        self._operatorStack = LinkedStack()
        self._scanner = scanner

    def translate(self):
        """Returns a list of tokens that represent the postfix
        form of sourceStr.  Assumes that the infix expression
        in sourceStr is syntactically correct"""
        postfix = list()
        for currentToken in self._scanner:
            self._expressionSoFar += str(currentToken) + " "
            if currentToken.getType() == Token.INT:
                postfix.append(currentToken)
            elif currentToken.getType() == Token.LPAR:
                self._operatorStack.push(currentToken)
            elif currentToken.getType() == Token.RPAR:
                topOperator = self._operatorStack.pop()
                while topOperator.getType() != Token.LPAR:
                    postfix.append(topOperator)
                    topOperator = self._operatorStack.pop()
            else:
                while not self._operatorStack.isEmpty() and \
                      self._operatorStack.peek().getPrecedence() >= \
                      currentToken.getPrecedence():
                    postfix.append(self._operatorStack.pop())
                self._operatorStack.push(currentToken)
        while not self._operatorStack.isEmpty():
            postfix.append(self._operatorStack.pop())
        return postfix

    def __str__(self):
        """Returns a string containing the contents of the expression
        processed and the stack to this point."""
        result = "\n"
        if self._expressionSoFar == "":
            result += "Portion of expression processed: none\n"
        else:
            result += "Portion of expression processed: " + \
                   self._expressionSoFar + "\n"
        if self._operatorStack.isEmpty():
            result += "The stack is empty"
        else:
            result += "Operators on the stack          : " + \
                      str(self._operatorStack)
        return result

    def translationStatus(self):
        return str(self)
Ejemplo n.º 4
0
def bracketsBalance(exp):
    #checks if the parentheses and brackets all match
    stk = LinkedStack()
    for l in exp: 
        if l in ['(','[']:
            stk.push(l) #push opening braces onto the stack
        elif l in [')',']']:
            if stk.isEmpty():
                return False #the list began with a closing bracket
            fromStack = stk.pop()
            if (l == '(' and fromStack != ')') or (l == '[' and fromStack != ']'):
                return False #non-matching symbols
    if stk.isEmpty(): return True #they all matched up
Ejemplo n.º 5
0
def bracketsBalance(exp):
    """exp is s string that represents the expression"""
    stk = LinkedStack()
    for ch in exp:
        if ch in ["[", "("]:
            stk.push(ch)
        elif ch in [']', ')']:
            if stk.isEmpty():
                return False
            chFromStck = stk.pop()
            if ch == ']' and chFromStck != '[' or \
            ch == ')' and chFromStck != '(' :
                return False
    return stk.isEmpty()
Ejemplo n.º 6
0
def bracketsBalance(exp):
    """exp is  a string that represents the expression """
    stk = LinkedStack()
    for ch in exp:
        if ch in ['[', '(']:
            stk.push(ch)
        elif ch in [']', ')']:
            if stk.isEmpty():
                return False
            chFromStack = stk.pop()
            # Brackets must be of same type and match up
            if ch == ']' and chFromStack != '[' or ch == ')' and chFromStack != '(':
                return False
    return stk.isEmpty()
Ejemplo n.º 7
0
def bracketsBalance(exp):
    """exp represents the expression"""
    stk = LinkedStack()  # Create a new stack
    for ch in exp:  # Scan across the expression
        if ch in ['[', '(']:  # Push an opening bracket
            stk.push(ch)
        elif ch in [']', ')']:  # Process a closing bracket
            if stk.isEmpty():  # Not balanced
                return False
            chFromStack = stk.pop()
            # Brackets must be of same type and match up
            if ch == ']' and chFromStack != '[' or \
               ch == ')' and chFromStack != '(':
                return False
    return stk.isEmpty()  # They all matched up
Ejemplo n.º 8
0
def bracketsBalance(exp):          
    """exp represents the expression"""
    stk = LinkedStack()                      # Create a new stack
    for ch in exp:                   # Scan across the expression
        if ch in ['[', '(']:            # Push an opening bracket 
            stk.push(ch)
        elif ch in [']', ')']:        # Process a closing bracket
            if stk.isEmpty():                      # Not balanced
                return False                  
            chFromStack = stk.pop()
            # Brackets must be of same type and match up
            if ch == ']' and chFromStack != '[' or \
               ch == ')' and chFromStack != '(':
                return False
    return stk.isEmpty()                   # They all matched up
Ejemplo n.º 9
0
    def is_palindrome(word: str) -> bool:
        """Check whether the word is a palindrome."""
        stack = LinkedStack()

        for index, char in enumerate(word, 1):
            if char.isalpha() and index <= len(word) / 2:
                stack.push(char)

            elif char.isalpha() and (index > len(word) / 2) \
                    and (index != (len(word) / 2) + 0.5):
                if stack.isEmpty():
                    return False

                char_from_stack = stack.pop()
                if char != char_from_stack:
                    return False

        return stack.isEmpty()
Ejemplo n.º 10
0
 def node_preorder(self):
     if not self.isEmpty():
         stack = LinkedStack()
         stack.push(self._root)
         while not stack.isEmpty():
             node = stack.pop()
             yield node
             if node.right != None:
                 stack.push(node.right)
             if node.left != None:
                 stack.push(node.left)
Ejemplo n.º 11
0
 def __iter__(self):
     """Supports a preorder traversal on a view of self."""
     if not self.isEmpty():
         stack = LinkedStack()
         stack.push(self._root)
         while not stack.isEmpty():
             node = stack.pop()
             yield node.data
             if node.right is not None:
                 stack.push(node.right)
             if node.left is not None:
                 stack.push(node.left)
Ejemplo n.º 12
0
 def preorder(self):
     """Supports a preorder traversal on a view of self."""
     if not self.isEmpty():
         treeStack = LinkedStack()
         treeStack.push(self._root)
         while not treeStack.isEmpty():
             node = treeStack.pop()
             yield node.data
             if node.right != None:
                 treeStack.push(node.right)
             if node.left != None:
                 treeStack.push(node.left)
Ejemplo n.º 13
0
 def preorder(self):
     """Supports a preorder traversal on a view of self."""
     if not self.isEmpty():
         treeStack = LinkedStack()
         treeStack.push(self._root)
         while not treeStack.isEmpty():
             node = treeStack.pop()
             yield node.data
             if node.right != None:
                 treeStack.push(node.right)
             if node.left != None:
                 treeStack.push(node.left)
Ejemplo n.º 14
0
    def successor(self, item):
        """
        Returns the smallest item that is larger than
        item, or None if there is no such item.
        :param item:
        :type item:
        :return:
        :rtype:
        """
        biggest = 0
        if not self.isEmpty():
            stack = LinkedStack()
            stack.push(self._root)
            while not stack.isEmpty():

                node = stack.pop()
                # print(smallest, node.data)
                if node.data >= biggest:
                    biggest = node.data
                if node.right != None:
                    stack.push(node.right)
                if node.left != None:
                    stack.push(node.left)
        smallest = biggest
        # print(smallest)
        if not self.isEmpty():
            stack = LinkedStack()
            stack.push(self._root)
            while not stack.isEmpty():

                node = stack.pop()
                # print(smallest, node.data)
                if item <= node.data <= smallest:
                    smallest = node.data
                if node.right != None:
                    stack.push(node.right)
                if node.left != None:
                    stack.push(node.left)
        # print(smallest)
        return smallest if smallest != 0 else None
Ejemplo n.º 15
0
    def levelorder(self):
        """Supports a levelorder traversal on a view of self."""
        if not self.isEmpty():
            stack = LinkedStack()
            stack.push(self.root)

            yield self.root.data
            while not stack.isEmpty():
                node = stack.pop()

                if node.left != None:
                    yield node.left.data
                    stack.push(node.right)
                if node.right != None:
                    yield node.right.data
                    stack.push(node.left)
Ejemplo n.º 16
0
def mazeSolver(maze, start, to_text=False, data_structure='stack'):
    """takes a maze and its starting point (as a tuple of row, column) and solves the maze. Maze walls must be *
    characters and the ending point must be a "T" character. Free spaces must be an empty space, " ". """
    # read the grid and set up stack
    grid = maze_reader(maze)
    print("maze without attempts:\n", grid)
    if data_structure == 'stack':
        _queue = LinkedStack()
    else:
        _queue = LinkedQueue(
        )  #TODO implement a linkedQueue structure with push
    _queue.push(start)
    # track choices:
    choice_count = 0
    #use stack data structure to explore maze and find a path to the end.
    while not _queue.isEmpty():
        _pop = _queue.pop()
        # print("popping ",_pop)
        if grid[_pop[0]][_pop[1]] == 'T':
            choice_count += 1
            print("Finished maze: \n")
            print(grid)
            if to_text:
                maze_text(grid, "solution.txt")
            return choice_count
        else:
            # if the _pop location did not return the character "T", leave a breadcrumb to not revisit.
            if grid[_pop[0]][_pop[1]] != 'O' and grid[_pop[0]][
                    _pop[1]] != 'T' and grid[_pop[0]][_pop[1]] != 'P':
                choice_count += 1
                grid[_pop[0]][_pop[1]] = 'O'
            # print("grid row, column is ",_pop[0],_pop[1],"\n")
            # print(grid)
            left = grid[_pop[0]][(_pop[1] - 1)]
            right = grid[_pop[0]][(_pop[1] + 1)]
            down = grid[(_pop[0] - 1)][_pop[1]]
            up = grid[(_pop[0] + 1)][_pop[1]]
            if left == ' ' or left == 'T':
                _queue.push((_pop[0], (_pop[1] - 1)))
            if right == ' ' or right == 'T':
                _queue.push((_pop[0], (_pop[1] + 1)))
            if up == ' ' or up == 'T':
                _queue.push(((_pop[0] + 1), _pop[1]))
            if down == ' ' or down == 'T':
                _queue.push(((_pop[0] - 1), _pop[1]))
    #if stack becomes empty, there is no path.
    return choice_count
Ejemplo n.º 17
0
class Polindrom(LinkedStack):
    """docstring for Polindrom."""
    def __init__(self):
        self.dictionary = LinkedStack()
        self.polindroms = []

    def read_dict(self, filename):
        """reads data from file and saves it to dictionary"""
        with open(filename, encoding='utf-8', errors='ignore') as f:
            lines = f.readlines()
            if ".lst" in filename:
                for line in lines:
                    self.dictionary.push(line.split()[0])
                # counter = 0
                # with open("try.txt", "w") as t:
                #     while counter < 30:
                #         t.write(lines[counter].split()[0]+"\n")
                #         counter += 1
                # self.dictionary.push(line.strip())
            else:
                for line in lines:
                    self.dictionary.push(line.strip())

    def process_dict(self):
        """looks for polindroms in processed dict and returns a list of them"""
        while not self.dictionary.isEmpty():
            isPolindrom = True
            curr_word = self.dictionary.pop()
            curr_word_len = len(curr_word)
            if curr_word_len > 1:
                for i in range(curr_word_len // 2):
                    if curr_word[i].lower() == curr_word[
                            curr_word_len - i - 1].lower() and isPolindrom:
                        isPolindrom = True
                    else:
                        isPolindrom = False
                if isPolindrom:
                    self.polindroms.append(curr_word)

    def write_dict(self, filename):
        """writes data from polindroms to file"""
        with open(filename, "w", encoding='utf-8', errors='ignore') as f:
            for item in self.polindroms:
                f.write(item)
                f.write("\n")
Ejemplo n.º 18
0
    def successor(self, item):  #FIXME: Incomplete
        succ = LinkedStack()

        def recurse(node, item):
            if node != None:
                if item >= node.data:
                    recurse(node.right, item)
                elif item < node.data:
                    succ.push(node.data)
                    recurse(node.left, item)

        if self.isEmpty():
            return None
        else:
            recurse(self.root, item)

        result = None
        if not succ.isEmpty():
            result = succ.pop()

        return result
Ejemplo n.º 19
0
    def predecessor(self, item):
        pred = LinkedStack()

        def recurse(node, item):
            if node != None:
                if item <= node.data:
                    recurse(node.left, item)
                elif item > node.data:
                    pred.push(node.data)
                    recurse(node.right, item)

        if self.isEmpty():
            return None
        else:
            recurse(self.root, item)

        result = None
        if not pred.isEmpty():
            result = pred.pop()

        return result
Ejemplo n.º 20
0
 def predecessor(self, item):
     """
     Returns the largest item that is smaller than
     item, or None if there is no such item.
     :param item:
     :type item:
     :return:
     :rtype:
     """
     biggest = 0
     if not self.isEmpty():
         stack = LinkedStack()
         stack.push(self._root)
         while not stack.isEmpty():
             node = stack.pop()
             if biggest <= node.data <= item:
                 biggest = node.data
             if node.right != None:
                 stack.push(node.right)
             if node.left != None:
                 stack.push(node.left)
     return biggest if biggest != 0 else None
Ejemplo n.º 21
0
    def rangeFind(self, low, high):
        '''
        Returns a list of the items in the tree, where low <= item <= high."""
        :param low:
        :param high:
        :return:
        '''

        lst = []

        if not self.isEmpty():
            stack = LinkedStack()
            stack.push(self._root)
            while not stack.isEmpty():
                node = stack.pop()
                if low <= node.data <= high:
                    lst.append(node.data)

                if node.right != None:
                    stack.push(node.right)
                if node.left != None:
                    stack.push(node.left)
        return lst
Ejemplo n.º 22
0
"""
Ejemplo n.º 23
0
"""
Ejemplo n.º 24
0
 def liclear_unit_test(self):
     temp = LinkedStack()
     for count in range(4):
           temp.push(count+1)
     temp.clear()
     self.assertEqual(temp.isEmpty(), True)