6: Stacks

Example 1: Page 113

In [1]:
#demonstrates stacks

class StackX:
	def __init__(self):	#special method to create objects
	#with instances customized to a specific initial state

		#since private instance variables don't exist in Python,
		#hence using a convention: name prefixed with an underscore, to treat them as non-public part
		self._stackVect = []	#stack list

	def push(self, j):	#put item on top
		self._stackVect.append(j)	#insert item

	def pop(self):	#take item from top
		return self._stackVect.pop()	#access item

	def peek(self):	#peek at top of stack
		return self._stackVect[-1]

	def isEmpty(self):	#true if stack is empty
		return not self._stackVect
#end class StackX

theStack = StackX()	#make new stack
theStack.push(20)	#push items onto stack
theStack.push(40)
theStack.push(60)
theStack.push(80)

while not theStack.isEmpty():	#until it's empty,
	value = theStack.pop()	#delete item from stack
	print value,	#display it
#end
80 60 40 20

Example 2: Page 116

In [1]:
#stack used to reverse a word

class StackX:
	def __init__(self):	#special method to create objects
	#with instances customized to a specific initial state

		#since private instance variables don't exist in Python,
		#hence using a convention: name prefixed with an underscore, to treat them as non-public part
		self._stackVect = []	#list used as stack

	def push(self, j):	#put item on top of stack
		self._stackVect.append(j)

	def pop(self):	#take item from top of stack
		return self._stackVect.pop()

	def peek(self):	#peek at top of stack
		return self._stackVect[-1]

	def isEmpty(self):	#true if stack is empty
		return not self._stackVect
#end class StackX

class Reverser:
	#since private instance variables don't exist in Python,
	#hence using a convention: name prefixed with an underscore, to treat them as non-public part
	
	#using In as in is reserved in Python
	def __init__(self, In):	#special method to create objects
	#with instances customized to a specific initial state
		self._input = In#input string
		self._output = ''	#output string

	def doRev(self):	#reverse the word
		theStack = StackX()	#make stack

		for j in self._input:	#get a char from _input
			theStack.push(j)	#push it
		while not theStack.isEmpty():
			ch = theStack.pop()	#pop a char,
			self._output += ch#append to _output
		return self._output
	#end doRev()
#end class Reverser

while True:
	#usin Input as input is reserved in Python
	Input = raw_input('Enter a word: ')	#read a word from kbd
	if len(Input) < 2:	#quit if one character
		break
		#make a Reverser
	theReverser = Reverser(Input)
	output = theReverser.doRev()	#use it
	print 'Reversed:', output
#end while
#end
Enter a word: part
Reversed: trap
Enter a word: 

Example 3: Page 120

In [3]:
#stacks used to check matching brackets

class StackX:
	def __init__(self):	#special method to create objects
	#with instances customized to a specific initial state

		#since private instance variables don't exist in Python,
		#hence using a convention: name prefixed with an underscore, to treat them as non-public part
		self._stackVect = []	#list used as stack

	def push(self, j):	#put item on top of stack
		self._stackVect.append(j)

	def pop(self):	#take item from top of stack
		return self._stackVect.pop()

	def peek(self):	#peek at top of stack
		return self._stackVect[-1]

	def isEmpty(self):	#true if stack is empty
		return not self._stackVect
#end class StackX

class BracketChecker:
	#using In as in is reserved in Python
	def __init__(self, In):#special method to create objects
	#with instances customized to a specific initial state

		#since private instance variables don't exist in Python,
		#hence using a convention: name prefixed with an underscore, to treat them as non-public part
		self._input = In#input string

	def check(self):
		theStack = StackX()	#make stack
		isError = False	#error flag

		for j, ch in enumerate(self._input):	#get chars in turn
			#since Python does not support switch, using if else ladder instead
			if ch in '{[(':	#opening symbols
				theStack.push(ch)	#push them

			elif ch in '}])':	#closing symbols
				if not theStack.isEmpty():	#if stack not empty,
					chx = theStack.pop()	#pop and check
					if (ch == '}' and chx != '{') or (ch == ']' and chx != '[') or (ch == ')' and chx != '('):
						isError = True
						print 'Mismatched delimeter:', ch, 'at', j
				else:	#prematurely empty
					isError = True
					print 'Misplaced delimeter:', ch, 'at', j
			#no action on other characters
			#end if else ladder
		#end for
		#at this point, all characters have been processed
		if not theStack.isEmpty():
			print 'Missing right delimeter'
		elif not isError:
			print 'OK'
	#end check()

#end clas BracketChecker

while True:
	#using Input as input is reserved in Python
	Input = raw_input('Enter string containing delimiters (no whitespace): ')	#read a string from kbd
	if len(Input) == 1:	#quit if 'q', etc.
		break
		#make a BracketChecker
	theChecker = BracketChecker(Input)
	theChecker.check()	#check brackets
#end while
#end
Enter string containing delimiters (no whitespace): a{b(c]d}e
Mismatched delimeter: ] at 5
Enter string containing delimiters (no whitespace): q