本文整理汇总了Python中Stack.top方法的典型用法代码示例。如果您正苦于以下问题:Python Stack.top方法的具体用法?Python Stack.top怎么用?Python Stack.top使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Stack
的用法示例。
在下文中一共展示了Stack.top方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: postOrderTravel
# 需要导入模块: import Stack [as 别名]
# 或者: from Stack import top [as 别名]
def postOrderTravel(self):
"""
Travel tree by post-order sequence
"""
newTree = self.clone()
if not newTree:
return
stack= Stack()
last = None
stack.push(newTree)
while stack.length():
item = stack.top()
if not item.getLeftChild() and not item.getRightChild() \
or last == item.getLeftChild() and not item.getRightChild() \
or last == item.getRightChild():
# visit the node who is either leaf node
# or node without right child and the left child has been visited
# or node whose right child is the last one been visited
print stack.pop().getValue()
last = item
else:
# push right child into stack first
if item.getRightChild():
stack.push(item.getRightChild())
# push left child into stack second
if item.getLeftChild():
stack.push(item.getLeftChild())
示例2: postOrderTravel2
# 需要导入模块: import Stack [as 别名]
# 或者: from Stack import top [as 别名]
def postOrderTravel2(self):
"""
second method of traveling tree by post-order sequence
"""
newTree = self.clone()
if not newTree:
return
stack = Stack()
# push tree into stack twice
stack.push(newTree)
stack.push(newTree)
while stack.length():
# pop out the first node
item = stack.pop()
# first pop pushes node's children into stack
# second pop visits the node
#
# if item equals the top item of stack means that item's children have not been visited yet
# then push them into stack
if stack.length() and item == stack.top():
if item.getRightChild():
stack.push(item.getRightChild())
stack.push(item.getRightChild())
if item.getLeftChild():
stack.push(item.getLeftChild())
stack.push(item.getLeftChild())
else:
print item.getValue()
示例3: RPNCalculator
# 需要导入模块: import Stack [as 别名]
# 或者: from Stack import top [as 别名]
class RPNCalculator(object):
'''
Information assumptions:
Maintains a stack containing current RPN expression evaluation values;
these are always numbers, but never the operators from an RPN expression.
'''
#------------------------------------------------------------------------------
#Constractor
def __init__(self):
'''
Pre:None
post: Creates an RPNCalculator object instance with an empty value stack
'''
self.stack = Stack()
#------------------------------------------------------------------------------
# push method
def push(self,item):
'''
pre: element is a numeric type
post: element is added to the value stack and becomes the current TOS,
with subsequent elements further along
Exceptions: TypeError if element is not a number
'''
#Raise an Type Error if the thing pushed in is not numeric
if not (isinstance(item,int) or isinstance(item,float) ):
raise TypeError('Give me a number please')
self.stack.push(item)
#------------------------------------------------------------------------------
#pop method
def pop(self):
'''
pre: value stack is not empty
post: value stack has the top-of-stack element removed and this is the
return value of the method
Exceptions: IndexError if stack is empty
'''
# If the stack is empty, Raise the Index Error
if len(self.stack) ==0:
raise IndexError('The Stack is already empty')
return self.stack.pop()
#------------------------------------------------------------------------------
#add method
def add(self):
'''
pre: value stack has at least two elements
post: top two elements have been popped off the value stack and their sum
has been pushed onto the value stack
Exceptions: IndexError if value stack does not have two elements
'''
#If the stack does not have at least two elements
#Raise IndexError
if len(self.stack) < 2:
raise IndexError ('Less than 2 numbers inside the stack')
#The Addition Process
# pop two elements off
# add/get result
#push it back to the top of the stack
a= self.stack.pop()
b = self.stack.pop()
c = b+a
self.stack.push(c)
#------------------------------------------------------------------------------
#Subtraction Method
def subtract(self):
'''
pre: value stack has at least two elements
post: Top two elements have been popped off the value stack and their subtraction result has been pushed onto the value stack
Exceptions: IndexError if value stack does not have two elements
'''
#If the stack does not have at least two elements
#Raise IndexError
if len(self.stack) < 2:
raise IndexError ('Less than 2 numbers inside the stack')
#The Subtraction Process
# pop two elements off
# subtract/get result
#push it back to the top of the stack
a= self.stack.pop()
b = self.stack.pop()
c = b-a
self.stack.push(c)
#------------------------------------------------------------------------------
#.........这里部分代码省略.........
示例4: __init__
# 需要导入模块: import Stack [as 别名]
# 或者: from Stack import top [as 别名]
#.........这里部分代码省略.........
token = statement.next()
string = string + ' ' + token
if string.endswith('"'):
break
print string[2:-1]
def expect(self):
count = int(self.stack.pop())
string = ''
while len(string) < count:
string = string + raw_input('... ')
for index in xrange(count):
self.stack.push(string[index])
def until_loop(self, statement):
loop_body = ''
pair = 1
while statement.has_next():
token = statement.next()
if token == 'UNTIL' and pair == 1:
pair -= 1
break
elif token == 'BEGIN':
pair += 1
elif token == 'UNTIL' and pair > 1:
pair -= 1
loop_body = loop_body + ' ' + token
if pair != 0:
raise NameError('Unmatched UNTIL Block')
while True:
# If not means if LEAVE occurred
if not self.process(loop_body, is_inside_until=True):
break
elif self.stack.top() == '0':
break
def do_loop(self, statement):
loop_body = ''
pair = 1
while statement.has_next():
token = statement.next()
if token == 'DO':
pair += 1
elif token == 'LOOP' and pair > 1:
pair -= 1
elif token == 'LOOP' and pair == 1:
pair -= 1
break
loop_body = loop_body + ' ' + token
if pair != 0:
raise NameError('Unmatched DO Block')
start = int(self.stack.pop())
end = int(self.stack.pop())
for i in xrange(start, end):
self.process(loop_body)
def handle_if(self, statement):
condition = bool(int(self.stack.pop())) #if the top was !=0 its True otherwise its False
if_body = ''
pair = 1
if condition:
while statement.has_next():
token = statement.next()
if token == 'IF':
pair += 1
elif token == 'ELSE' and pair == 1: # if pair was one ELSE is for the current if
示例5: print
# 需要导入模块: import Stack [as 别名]
# 或者: from Stack import top [as 别名]
#https://www.cs.auckland.ac.nz/courses/compsci105ssc/resources/ProblemSolvingwithAlgorithmsandDataStructures.pdf
print("------------Starting Stack Testing------------")
#Stack
from Stack import *
s = Stack()
#Operations #Stack Contents #Return Value
print(s.is_empty()) #[] True
s.push(4) #[4]
s.push('dog') #[4,'dog']
print(s.top()) #[4,'dog'] 'dog'
print(s.push(True)) #[4,'dog',True]
print(s.size()) #[4,'dog',True] 3
print(s.is_empty()) #[4,'dog',True] False
print(s.push(8.4)) #[4,'dog',True,8.4]
print(s.pop()) #[4,'dog',True] 8.4
print(s.pop()) #[4,'dog'] True
print(s.size()) #[4,'dog'] 2
print("------------Starting Queue Testing------------")
#Queue
from Queue import *
q = Queue()