标签:ddl initial ext family nta index bee plist 替代
s1 = ArrayStack() s2 = LinkedStack( [20, 40, 60] ) |
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Lijunjie
""" File: brackets.py Checks expressions for matching brackets. """
from linkedstack import LinkedStack
def bracketsBalance( exp, startBracketList = [‘(‘, ‘[‘], endBracketList = [‘)‘, ‘]‘] ): """exp is a string that represents the expressions. startBracketList is the list of start brackets list. endBracketList is the list of end brackets list. precondition: startBracketList must have the same length of endBracketList. raise: Exception if startBracketList don‘t have the same length of endBracketList."""
if len( startBracketList ) != len( endBracketList ): raise Exception( "The startBracketList must have the same length with the endBracketList." )
stk = LinkedStack() for ch in exp: if ch in startBracketList: stk.push( ch ) elif ch in endBracketList: if stk.isEmpty(): return False chFromStack = stk.pop() if chFromStack != startBracketList[ endBracketList.index( ch ) ]: return False return stk.isEmpty()
def main(): """Test the bracketsBalance function.""" while True: exp = input( "Enter a brackets expressions: ") if exp == "": break if bracketsBalance(exp,[‘(‘,‘[‘, ‘{‘],[‘)‘, ‘]‘, ‘}‘] ): print("OK!") else: print( "Not OK!" )
if __name__ == "__main__": main() |
Create an empty stack Push the starting state onto the stack while the stack in not empty: Pop the stack and eaxmine the state if the state represents an ending state return SUCCESSFUL CONCLUSION elif the state hasn‘t been visited previously Mark the state as visited Push onto the stack all unvisited adjacent states. return UNSUCCESSFUL CONCLUSION |
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Lijunjie
""" File: teststack.py A tester program for stack implementations. """
# from arraystack import ArrayStack from linkedstack import LinkedStack
def test( stackType ): """Test any implementation with the same code.""" s = stackType() print( "Length: ", len( s ) ) print( "Empty: ", s.isEmpty ) print( "Push 1-10" ) for i in range( 10 ): s.push( i + 1 ) print( "Peeking: ", s.peek() ) print( "Item ( bottom to top ): ", s ) print( "Length: ", len( s ) ) print( "Empty: ", s.isEmpty ) theClone = stackType( s ) print( "Items in clone ( bottom to top ): ", theClone ) theClone.clear() print( "Length of clone after clear: ", len( theClone ) ) print( "Push 11" ) s.push( 11 ) print( "Poping items( top to bottom):", end = "" ) while not s.isEmpty():print( s.pop(), end = " " ) print( "\nLength: ", len( s ) ) print( "Empty: ", s.isEmpty() ) print( "Test precondition of pop." ) try: s.pop() except KeyError: print( "KeyError" ) print( "Test precondition of peek." ) try: s.peek() except KeyError: print( "KeyError" )
# test( ArrayStack ) test( LinkedStack ) |
##!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Lijunjie
from abstractstack import AbstractStack from arrays import Array
class ArrayStack( AbstractStack ): """An array-based stack."""
#Class variable DEFAULT_CAPACITY = 10
def __init__( self, sourceCollection = None ): """Sets the initial state of self, which includes the contents of sourceCollection, if it‘s present.""" self._items = Array( ArrayStack.DEFAULT_CAPACITY ) AbstractStack.__init__( self, sourceCollection )
# Accessor method def __iter__( self ): """Support iteration over a view of self. From bottom to top.""" cursor = 0 while cursor < len( self ): yield self._items[ cursor ] cursor += 1
def peek( self ): """Returns the items at top of the stack Precondition: stack is not empty. Raise: KeyError if stack is empty""" if self.isEmpty(): raise KeyError( "The stack is empty." ) return self._items[len(self) - 1]
# Mutator method def clear( self ): """Clear the stack.""" self._items = Array( ArrayStack.DEFAULT_CAPACITY ) self._size = 0
def push( self, item ): """Push an item at the top of the stack""" # Resize the array if necessary. self.grow() self._size += 1 self._items[len(self) - 1] = item
def pop( self ): """ Returns and remove the item at the top of the stack. precondition: the stack is not empty. raise: raise KeyError if the stack is empty.""" if self.isEmpty(): raise KeyError( "The stack is empty." ) oldItem = self._items[ len(self) - 1 ] self._size -= 1 # Resize the array if necessary. self.shrink() return oldItem
def grow( self ): """Grow the capacity of the array if necessary """ physicalSize = len( self._items ) if len( self ) >= physicalSize: temp = Array( physicalSize * 2 ) index = 0 for item in self: temp[index] = item index += 1 self._items = temp
def shrink( self ): """Shrink the capacity of the array if necessary. """ physicalSize = len( self._items ) if len( self ) <= physicalSize // 4 and physicalSize >= 2 * ArrayStack.DEFAULT_CAPACITY: temp = Array( physicalSize//2 ) index = 0 for item in self: temp[index] = item index += 1 self._items = temp |
##!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Lijunjie
from abstractstack import AbstractStack from node import Node
class LinkedStack( AbstractStack ): """An linked-based stack."""
def __init__( self, sourceCollection = None ): """Sets the initial state of self, which includes the contents of sourceCollection, if it‘s present.""" self._items = None AbstractStack.__init__( self, sourceCollection )
# Accessor method def __iter__( self ): """Support iteration over a view of self. From bottom to top.""" def visitNode( node ): if node != None: visitNode( node.next ) tempList.append( node.data ) tempList = list() visitNode( self._items ) return( iter( tempList ) )
def peek( self ): """Returns the items at top of the stack Precondition: stack is not empty. Raise: KeyError if stack is empty""" if self.isEmpty(): raise KeyError( "The stack is empty." ) return self._items.data
# Mutator method def clear( self ): """Clear the stack.""" self._items = None self._size = 0
def push( self, item ): """Push an item at the top of the stack""" # Resize the array if necessary. self._size += 1 self._items = Node( item, self._items )
def pop( self ): """ Returns and remove the item at the top of the stack. precondition: the stack is not empty. raise: raise KeyError if the stack is empty.""" if self.isEmpty(): raise KeyError( "The stack is empty." ) oldItem = self._items.data self._items = self._items.next self._size -= 1 return oldItem
|
##!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Lijunjie
""" File name: abstractstack.py """
from abstractcollection import AbstractCollection
class AbstractStack( AbstractCollection ): """ An abstract stack class """
#Constructor def __init__( self, sourceCollection = None ): """Sets the initial state of self, which includes the contents of sourceCollection, if it‘s present.""" AbstractCollection.__init__( self, sourceCollection )
# Mutator method def add( self, item ): """Add item to self""" self.push( item ) |
PFEvaluatorView() Create and saves a reference to the model.
run() while True: Retrieve the expressions string from keyboard. Send it to the model for fromating and print the format string. Send it to the model for evaluation. Either print the value or catch exceptions raised by the evaluator. ask the model for the associated details, and display error. messages.
|
format( expressionStr ): Instantiate a scanner on the expression string. Build a response string by iterating acorss the scanner and appending a string representation of each token to the response string. Return the reponse string.
evaluate( expressionStr ): Ask the evaluator to evaluate the expression string. Return the value.
evaluationStatus(): Ask the evaluator for its status. Return the status
|
PFEvaluator( scanner ) Intialize expressionSoFar Instantiate an ArrayStack Save a reference to the scanner
evaluate() Iterate across the scanner and evaluate the expression. Raise exception in the following situation: The scanner is None or empty There are too many operands There are too few operands There are unrecognizable tokens. A divide by 0 exception is raised by the PVM
evaluationStatus() Return a multipart stirng that contains the portion of the expression processed and the contents of the stack.
|
Scanner( sourceStr ): Save a reference to the string that will be scanned and tokenized
hasNext() Return True if the string contains another token and False otherwise.
next() Return the next token. Raise an exception if hasnext() return False.
|
UNKNOWN = 0 #unknow INT = 4 #interger MINUS = 5 #minus operator PLUS = 6 #plus operator MUL = 7 #multiply operator DIV = 8 #divide operator
|
Token( vlaue ): Construct a new integer token with the specified value
Token(ch): if ch is an operator( + - * / ), then construct a new operator token; otherwise, construct a token of unknow type.
getType() return a token‘s type
getValue() return a token‘s value.
isOperator(): Return True if the token is an operator, and False Otherwise
__str__(): Retrun the token‘s numeric value as a string if the token is an integer; otherwise, return the token‘s character representation.
|
标签:ddl initial ext family nta index bee plist 替代
原文地址:https://www.cnblogs.com/lijunjie9502/p/9892559.html