Exemple #1
0
def isValidSource(srcFile):
    """
    The function accepts a file object, which we assume was previously opened and contains C++
    source code.The file is scanned one line at a time and each line is scanned one character
    at a time to determine if it contains properly paired and balanced delimiters.
    """
    s = Stack()
    for line in srcFile:
        for token in line:
            if token in "{[(":
                # if token is one of the opening delimiters it should be pushed
                # into the stack.
                s.push(token)
            # if token is one of the closing delimiters it should be checke by
            # the following steps.
            elif token in ")]}":
                if s.isEmpty():
                    return False
                else:
                    left = s.pop()
                    if token == "}" and left != "{" or \
                            token == "]" and left != "[" or \
                            token == ")" and left != "(":
                        return False
    return s.isEmpty()
Exemple #2
0
class _BSTMapIterator:
    """ Iterator for the binary search tree using a software stack """
    def __init__(self, root):
        """Create a stack for use in traversing the tree. """
        self._theStack = Stack()
        self._traverseToMinNode(root)

    def __iter__(self):
        return self

    def next(self):
        """Returns the next item from the BST in key order"""
        # If the stack is empty, we are done.
        if self._theStack.isEmpty():
            raise StopIteration
        else:       # The top node on the stack contains the next key.
            node = self._theStack.pop()
            key = node.key
            # If this node has a subtree rooted as the right child, we must
            # find the node in that subtree that contains the smallest key.
            # Again, the nodes along the path are pushed on the stack.
            if node.right is not None:
                self._traverseToMinNode(node.right)
            return key

    def _traverseToMinNode(self, subtree):
        """ Traverses down the subtree to find the node containing the
        smallest key during which the nodes along that path are pushed onto
        the stack."""
        if subtree is not None:
            self._theStack.push(subtree)
            self._traverseToMinNode(subtree.left)
Exemple #3
0
    def find_path(self):
        stack = Stack()
        current = self.startCell
        current.path.append(current)
        current.parent = current

        if current == self.exitCell:
            return True
        home_cords_nei = self.check_neighbors(current.row, current.col)
        for cell in home_cords_nei:
            if cell == self.exitCell:
                return True
            cell.path.append(current)
            stack.push(cell)
        self.mark_tried(current.row, current.col)

        while not stack.isEmpty():
            parent = current
            current = stack.peek()
            current.parent = parent
            current.path += parent.path
            current.path.append(current)

            self.mark_tried(current.row, current.col)
            if self.exit_found(current.row, current.col):
                self.exit = current
                return True
            stack.pop()
            for cell in self.check_neighbors(current.row, current.col):
                stack.push(cell)
        return False
Exemple #4
0
    def findPath(self):
        paths = Stack()
        paths.push(self._startCell)
        while not paths.isEmpty():
            currCell = paths.pop()
            self._markTried(currCell.row, currCell.col)
            if currCell.row == self._exitCell.row and currCell.col == self._exitCell.col:
                currCell.path.append(currCell)
                for el in currCell.path:
                    self._markPath(el.row, el.col)
                return True
            if self._validMove(currCell.row + 1, currCell.col):
                paths.push(
                    _CellPosition(currCell.row + 1, currCell.col, currCell))
            if self._validMove(currCell.row - 1, currCell.col):
                paths.push(
                    _CellPosition(currCell.row - 1, currCell.col, currCell))
            if self._validMove(currCell.row, currCell.col + 1):
                paths.push(
                    _CellPosition(currCell.row, currCell.col + 1, currCell))
            if self._validMove(currCell.row, currCell.col - 1):
                paths.push(
                    _CellPosition(currCell.row, currCell.col - 1, currCell))

        return False
Exemple #5
0
def isValidSource(srcfile):
    s = Stack()
    for line in srcfile:
        for token in line:
            if token in "{[(":
                s.push(token)
            elif token in "}])":
                if s.isEmpty():
                    return False
                else:
                    left = s.pop()
                    if (token == "}" and left != "{") or \
                            (token == "]" and left != "[") or \
                            (token == ")" and left != "("):
                        return False
    return s.isEmpty()
Exemple #6
0
 def findPath( self ):
     traceAcct = Stack()
     curPos = _CellPosition(self._startCell.row, self._startCell.col)
     if not self._validMove(curPos.row, curPos.col):
         return False
     self._markPath(curPos.row, curPos.col)
     trapFlag = False
     while True:
         for i in range(4): # Left, Up, Right, Down
             candidatePos = _CellPosition(curPos.row + self.DIRECT[i][0], \
                                        curPos.col + self.DIRECT[i][1])
             if self._validMove(candidatePos.row, candidatePos.col):
                 traceAcct.push(curPos)
                 curPos = candidatePos
                 self._markPath(curPos.row, curPos.col)
                 if self._exitFound(curPos.row, curPos.col):
                     return True
                 break
             if i == 3:
                 trapFlag = True
             continue
         if trapFlag:
             trapFlag = False
             self._markTried(curPos.row, curPos.col)
             if traceAcct.isEmpty():
                 return False
             else:
                 curPos = traceAcct.pop()
Exemple #7
0
    def findPath(self):
        s = Stack()  #stack to save the path
        s.push(self._startCell)
        self._markPath(self._startCell.row, self._startCell.col)
        while True:
            #inside the loop where neighbor cell is checked for valid move
            #same time, checked if we get the exit
            if s.isEmpty():
                return False
            current_cell = s.peek()
            row = current_cell.row
            col = current_cell.col
            if not self._exitFound(row, col):
                for r in [row - 1, row, row + 1]:
                    if not (current_cell.row == s.peek().row and \
                            current_cell.col == s.peek().col):
                        break
                    for c in [col - 1, col, col + 1]:
                        if ((r == row) ^ (c == col)):
                            if self._validMove(r, c):
                                self._markPath(r, c)
                                s.push(_CellPosition(r, c))
                                break
                if current_cell.row == s.peek().row and\
                        current_cell.col == s.peek().col:
                    not_in_path = s.pop()
                    self._markTried(not_in_path.row, not_in_path.col)

            else:
                return True
Exemple #8
0
    def findPath(self):
        """
        finds  path in a Maze and Returns True
        if no path it will return None
        """
        maze_stack = Stack()
        maze_stack.push(self._startCell)
        current_cell = self._startCell
        self._markPath(self._startCell.row, self._startCell.col)
        while not maze_stack.isEmpty():
            possible_moves = [(-1, 0), (0, 1), (1, 0), (0, -1)]

            current_cell.row = maze_stack.peek().row
            current_cell.col = maze_stack.peek().col

            self._markPath(current_cell.row, current_cell.col)

            moved = False
            for i, j in possible_moves:
                if self._validMove(current_cell.row + i, current_cell.col + j):
                    current_cell.row = current_cell.row + i
                    current_cell.col = current_cell.col + j
                    maze_stack.push(
                        _CellPosition(current_cell.row, current_cell.col))
                    moved = True
                    break
            if moved:
                if self._exitFound(current_cell.row, current_cell.col):
                    self._markPath(current_cell.row, current_cell.col)
                    return True
                continue
            visited_cell = maze_stack.pop()
            self._markTried(visited_cell.row, visited_cell.col)
Exemple #9
0
class _BSTMapIterator:
    def __init__(self, root):
        # Creates a stack for use in traversing the tree.
        self._theStack = Stack()
        self._traverseToMinNode(root)

    def __iter__(self):
        return self

    # Returns the next item from the BST in key order.
    def __next__(self):
        # If the stack is empty, we are done.
        if self._theStack.isEmpty():
            raise StopIteration
        else:
            # The top node on the stack contains the next key.
            node = self._theStack.pop()
            key = node.key

            # If this node has a subtree rooted as the right child, we must
            # find the node in that subtree that contains the smallest key.
            # Again, the nodes along the path are pushed onto the stack.
            if node.right is not None:
                self._traverseToMinNode(node.right)

            return key

    # Traverses down the subtree to find the node containing the smallest
    # key during which the nodes along that path are pushed onto the stack.
    def _traverseToMinNode(self, subtree):
        if subtree is not None:
            self._theStack.push(subtree)
            self._traverseToMinNode(subtree.left)
class _BSTMapIterator:
    def __init__( self, root ):
        self._theStack = Stack()
        # traverse down to the node containing the smallest key during
        # which each node along the path is pushed onto the stack
        self._traverseToMinNode( root )

    def __iter__( self ):
        return self

    # Returns the next item from the BST in key order.
    def next( self ):
        # If the stack is empty, we are done..
        if self._theStack.isEmpty():
            raise StopIteration
        else:
            # The top node on the stack contains the key.
            node = self._theStack.pop()
            key = node.key
            # If this node has a subtree rooted as the right child, we must
            # fiind the node in that subtree that contains the smallest key.
            # Again, the nodes along the path are pushed onto the stack.
            if node.right is not None:
                self._traverseToMinNode( node.right )
            return key

    def _traverseToMinNode( self, subtree ):
        if subtree is not None:
            self._theStack.push( subtree )
            self._traverseToMinNode( subtree.left )
Exemple #11
0
class _T23Iter:
    """ Iterator for the 2-3 tree using a software stack """

    FIRST_KEY = 0
    SECOND_KEY = 1

    LEFT_BRANCH = 0
    MID_BRANCH = 1
    RIGHT_BRANCH = 2

    def __init__(self, root):
        """Create a stack for use in traversing the tree. """
        self._theStack = Stack()
        if root is not None:
            self._theStack.push((root, _T23Iter.FIRST_KEY))
            self._traverseToMinNode(root, _T23Iter.LEFT_BRANCH)

    def __iter__(self):
        return self

    def next(self):
        """Returns the next item from the BST in key order"""
        # If the stack is empty, we are done.
        if self._theStack.isEmpty():
            raise StopIteration
        else:       # The top node on the stack contains the next key.
            (node, which) = self._theStack.pop()
            if node.isLeaf() and which == _T23Iter.FIRST_KEY:
                key = node.key1
                if node.isFull():
                    self._theStack.push((node, _T23Iter.SECOND_KEY))
            elif node.isLeaf() and which == _T23Iter.SECOND_KEY:
                key = node.key2
            elif not node.isLeaf() and which == _T23Iter.FIRST_KEY:
                key = node.key1
                if node.isFull():
                    self._theStack.push((node, _T23Iter.SECOND_KEY))
                self._traverseToMinNode(node, _T23Iter.MID_BRANCH)
            else: # not node.isLeaf() and which == _T23Iter.SECOND_KEY:
                key = node.key2
                self._traverseToMinNode(node, _T23Iter.RIGHT_BRANCH)
            return key

    def _traverseToMinNode(self, node, branch):
        """ Traverses down <node>'s branch indecated by <branch> to find
        the node containing the in-order successor"""
        if not node.isLeaf():
            if branch == _T23Iter.LEFT_BRANCH:
                node = node.left
            elif branch == _T23Iter.MID_BRANCH:
                node = node.middle
            else: # branch == _T23Iter.RIGHT_BRANCH
                node = node.right
            self._theStack.push((node, _T23Iter.FIRST_KEY))
            while not node.isLeaf():
                node = node.left
                self._theStack.push((node, _T23Iter.FIRST_KEY))
def printListStack(head):

    s = Stack()
    curNode = head
    while curNode is not None:
        s.push(curNode.data)
        curNode = curNode.next
    while not s.isEmpty():
        item = s.pop()
        print item
def printListStack(head):

	s = Stack()
	curNode = head
	while curNode is not None:
		s.push(curNode.data)
		curNode = curNode.next
	while not s.isEmpty():
		item = s.pop()
		print item
class ExtoPostfix:
	"""
	Receive an infix expression and turn it into a postfix expression.
	This is a helper module of postfixCal.py.
	"""
	def __init__(self):
		self._isp = {'#':0, '(':1, '*':5, '/':5, '+':3, '-':3, ')':6}	#in stack priority
		self._icp = {'#':0, '(':6, '*':4, '/':4, '+':2, '-':2, ')':1}	#in coming priority
		self._postfix = []		#the list used to save the final postfix expression.
		self._oprtStack = Stack()	#the stack used to change the order of operators.

	def __str__(self):
		self._postfix = [elem for elem in self._postfix if elem != ')' and elem != '(']
		return ','.join(self._postfix)

	def _getPostfix(self,expr):
		"""
		Algorithm:
		1)initialize the _oprtStack by pushing '#' into it.
		2)read in the first element of the infix expr, and assign it to variable ch.
		3)repeat the following steps until ch = '#', meanwhile, the top element of the _oprtStack is also '#':
			a)if ch is operand, append it to the _postfix, and read the next ch;
			b)if ch is operator, compare the priority(icp) of ch and the priority(isp) of the top element(op) in  _oprtStack:
				if icp(ch) > isp(op), push ch onto _oprtStack, and read another ch
				if icp(ch) < isp(op), pop the top element in _oprtStack, and append it to _postfix
				if icp(ch) == isp(op), pop the top element in _oprtStack,if op is '(', read another ch.
		"""
		expr = expr.split()
		self._oprtStack.push('#')
		ch = expr.pop(0)
		while self._oprtStack.isEmpty()==False and ch != '#':
				if ch.isdigit():
						self._postfix.append(ch)
						ch = expr.pop(0)
				else:
						ch1 = self._oprtStack.peek()
						if self._isp[ch1] < self._icp[ch]:
								self._oprtStack.push(ch)
								ch = expr.pop(0)
						elif self._isp[ch1] > self._icp[ch]:
								out = self._oprtStack.pop()
								self._postfix.append(out)
						else:
								out = self._oprtStack.pop()
								if out == '(':
										ch = expr.pop(0)

		for i in range(len(self._oprtStack)-1):
				ch1 = self._oprtStack.pop()
				self._postfix.append(ch1)

	def backExpr(self,expr):
		self._getPostfix(expr)
		return self._postfix
    def findPath( self ):
        stack = Stack()
        self._markPath(self._startCell.row, self._startCell.col) 

        stack.push(self._startCell)
        
        while not stack.isEmpty():
            # debug
            stack.show()     

            cur = _CellPosition(0, 0)
            cur.row = stack.peek().row
            cur.col = stack.peek().col
            print "current:"
            print (cur.row, cur.col) 
            if cur.row == self._exitCell.row and \
               cur.col == self._exitCell.col:
                print "findPath ok"
                return 1

            if self.haveUp(cur.row, cur.col):
                cur.row = cur.row - 1
                stack.push(cur)
                self._markPath(cur.row, cur.col) 
                continue

            if self.haveRight(cur.row, cur.col):
                cur.col = cur.col + 1
                stack.push(cur)
                self._markPath(cur.row, cur.col) 
                continue
            
            if self.haveDown(cur.row, cur.col):
                cur.row = cur.row + 1
                stack.push(cur)
                self._markPath(cur.row, cur.col) 
                continue
            
            if self.haveLeft(cur.row, cur.col):
                cur.col = cur.col - 1
                stack.push(cur)
                self._markPath(cur.row, cur.col) 
                continue

            print "aaaaaaaaaaaaa"
            self._markTried(cur.row, cur.col) 
            stack.pop() 
            stack.show()     
            

        print "findPath fail"
        return 0
def printListStack(head):
    # Createe a stack to store the items
    s = Stack()
    # Iterate throught the list and push each item onto the stack
    curNode = head
    while curNode is not None:
        s.push(curNode.data)
        curNode = curNode.next

    # Repeatedly pop the items from the stack and print them until the stack is empty
    while not s.isEmpty():
        item = s.pop()
        print item
def printListStack( head ):
    from lliststack import Stack

    s = Stack()

    # Iterate through the list and push each item onto the stack
    curNode = head
    while curNode is not None:
        s.push( curNode.data )
        curNode = curNode.next

    # Repeatedly pop the items from the stack and print them
    while not s.isEmpty():
        item = s.pop()
        print item,
    print ''
Exemple #18
0
 def find_path(self):
     if not self.maze_cells[self.exit_cell.row, self.exit_cell.col] is None:
         return False
     tmp = Stack()
     i, j = self.start_cell.row, self.start_cell.col
     dead_ends = [self.CELL_PATH, self.CELL_TRIED, self.CELL_WALL]
     directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
     tmp.push([i, j])
     self.maze_cells[i, j] = self.CELL_PATH
     while True:
         for direction in directions:
             try:
                 i1, j1 = i + direction[0], j + direction[1]
                 t = self.maze_cells[i1, j1]
             except IndexError:
                 continue
             while self.maze_cells[i1, j1] \
                     not in dead_ends:
                 i += direction[0]
                 j += direction[1]
                 tmp.push([i, j])
                 self.maze_cells[i, j] = self.CELL_PATH
                 if i == self.exit_cell.row and j == self.exit_cell.col:
                     return True
                 if i == self.start_cell.row and j == self.start_cell.col:
                     return False
         if self.check_cell(i, j) is None:
             while True:
                 coor = tmp.pop()
                 if tmp.isEmpty():
                     return False
                 self.maze_cells[coor[0], coor[1]] = self.CELL_TRIED
                 coor = tmp.peek()
                 tmpcoor = self.check_cell(coor[0], coor[1])
                 if tmpcoor:
                     i, j = coor[0], coor[1]
                     break
         if i == self.start_cell.row and j == self.start_cell.col:
             return False
         if i == self.exit_cell.row and j == self.exit_cell.col:
             return True
Exemple #19
0
 def findPath(self):
     stack_path = Stack()
     stack_path.push(self._startCell)
     while not stack_path.isEmpty():
         use_cell = stack_path.pop()
         self._markTried(use_cell.row, use_cell.col)
         if use_cell.row == self._exitCell.row and use_cell.col == self._exitCell.col:
             use_cell.path.append(use_cell)
             for i in use_cell.path:
                 self._markPath(i.row, i.col)
             return True
         if self._validMove(use_cell.row + 1, use_cell.col):
             stack_path.push(
                 _CellPosition(use_cell.row + 1, use_cell.col, use_cell))
         if self._validMove(use_cell.row - 1, use_cell.col):
             stack_path.push(
                 _CellPosition(use_cell.row - 1, use_cell.col, use_cell))
         if self._validMove(use_cell.row, use_cell.col + 1):
             stack_path.push(
                 _CellPosition(use_cell.row, use_cell.col + 1, use_cell))
         if self._validMove(use_cell.row, use_cell.col - 1):
             stack_path.push(
                 _CellPosition(use_cell.row, use_cell.col - 1, use_cell))
     return False
# Test the Stack

#from liststack import Stack
from lliststack import Stack

PROMPT = "Enter an int value (<0 to end): "
myStack = Stack()
value = int(input( PROMPT ))
while value >= 0:
    myStack.push( value )
    value = int(input( PROMPT ))

while not myStack.isEmpty():
    value = myStack.pop()
    print( value )
Exemple #21
0
class ExtoPostfix:
    """
    Receive an infix expression and turn it into a postfix expression.
    This is a helper module of postfixCal.py.
    """
    def __init__(self):
        self._isp = {
            '#': 0,
            '(': 1,
            '*': 5,
            '/': 5,
            '+': 3,
            '-': 3,
            ')': 6
        }  # in stack priority
        self._icp = {
            '#': 0,
            '(': 6,
            '*': 4,
            '/': 4,
            '+': 2,
            '-': 2,
            ')': 1
        }  # in coming priority
        # the list used to save the final postfix expression.
        self._postfix = []
        # the stack used to change the order of operators.
        self._oprtStack = Stack()

    def __str__(self):
        self._postfix = [
            elem for elem in self._postfix if elem != ')' and elem != '('
        ]
        return ','.join(self._postfix)

    def _getPostfix(self, expr):
        """
        Algorithm:
        1)initialize the _oprtStack by pushing '#' into it.
        2)read in the first element of the infix expr, and assign it to variable ch.
        3)repeat the following steps until ch = '#', meanwhile, the top element of the _oprtStack is also '#':
                a)if ch is operand, append it to the _postfix, and read the next ch;
                b)if ch is operator, compare the priority(icp) of ch and the priority(isp) of the top element(op) in  _oprtStack:
                        if icp(ch) > isp(op), push ch onto _oprtStack, and read another ch
                        if icp(ch) < isp(op), pop the top element in _oprtStack, and append it to _postfix
                        if icp(ch) == isp(op), pop the top element in _oprtStack,if op is '(', read another ch.
        """
        expr = expr.split()
        self._oprtStack.push('#')
        ch = expr.pop(0)
        while self._oprtStack.isEmpty() == False and ch != '#':
            if ch.isdigit():
                self._postfix.append(ch)
                ch = expr.pop(0)
            else:
                ch1 = self._oprtStack.peek()
                if self._isp[ch1] < self._icp[ch]:
                    self._oprtStack.push(ch)
                    ch = expr.pop(0)
                elif self._isp[ch1] > self._icp[ch]:
                    out = self._oprtStack.pop()
                    self._postfix.append(out)
                else:
                    out = self._oprtStack.pop()
                    if out == '(':
                        ch = expr.pop(0)

        for i in range(len(self._oprtStack) - 1):
            ch1 = self._oprtStack.pop()
            self._postfix.append(ch1)

    def backExpr(self, expr):
        self._getPostfix(expr)
        return self._postfix
from lliststack import Stack

values = Stack()

for i in range(16):
    if i % 3 == 0:
        values.push(i)
    elif i % 4 == 0:
        values.pop()

while not values.isEmpty():
    print(values.pop())