这是自己做的练习,可能有错误,欢迎讨论和各种优化重构方案。
根据反馈,或者code review,对本篇文章答案或者相关内容的更新补充,一般会被添加在本篇博客的评论中。
将尽量保证每题的答案代码是完整的,不仅仅是函数或者类,打开Python 2.7的IDLE,将代码完整拷贝进去,就能调试运行。
欢迎访问Balian在博客园的家。 http://www.cnblogs.com/balian
13-8.
堆栈类。一个堆栈(stack)是一种具有后进先出(last-in-first-out,LIFO)特性的数据结构。我们可以把它想象成一个餐盘架。最先放上去的盘子将是最后一个取下来的,而最后一个放上去的盘子是最先被取下来的。博主:这有点像子弹夹,最先压下去的子弹在最后被射出。你的类中应该有push()方法(向堆栈中压入一个数据项)和pop()方法(从堆栈中移出一个数据项)。还有一个叫isempty()的布尔方法。如果堆栈是空的,返回布尔值1,否则返回0;一个名叫peek()的方法,取出堆栈顶部的数据项,但并不移除它。
注意,如果你使用一个列表来实现堆栈,那么pop()方法从Python1.5.2版本起已经存在了。那就在你编写的新类里,加上一段代码检查pop()方法是否已经存在。如果经检查pop()方法存在,就调用这个内建的方法;否则就执行你自己编写的pop()方法。你很可能要用到列表对象;如果用到它时,不需要担心实现列表的功能(例如切片)。只要保证你写的堆栈类能够正确实现上面的两项功能就可以了。你可以用列表对象的子类或自己写个类似列表的对象,请参考示例6.2。
【注】
书142页,提到了检查列表类型的内建函数的方法。博主使用Python 2.7,自然能找到pop()方法。
Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\>python Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> dir(list) [\'__add__\', \'__class__\', \'__contains__\', \'__delattr__\', \'__delitem__\', \'__delslice__\', \'__doc__\', \'__eq__\', \'__format__\', \'__ge__\', \'__getattribute__\' , \'__getitem__\', \'__getslice__\', \'__gt__\', \'__hash__\', \'__iadd__\', \'__imul__\', \'__init__\', \'__iter__\', \'__le__\', \'__len__\', \'__lt__\', \'__mul__\', \'__ne __\', \'__new__\', \'__reduce__\', \'__reduce_ex__\', \'__repr__\', \'__reversed__\', \'__rmul__\', \'__setattr__\', \'__setitem__\', \'__setslice__\', \'__sizeof__\', \'__ str__\', \'__subclasshook__\', \'append\', \'count\', \'extend\', \'index\', \'insert\', \'pop\', \'remove\', \'reverse\', \'sort\']
一小段程序就能用来检查dir(list)的输出结果(其实是一个列表)中是否有“pop”:
def findPop(): result = False for i in dir(list): if i == \'pop\': result = True break return result
另外,这个用于堆栈的列表,list[0]是栈底,list[-1]是栈顶。
【答案】
代码如下:
#-*- encoding: utf-8 -*- class StackPattern(object): \'定义堆栈模型类\' def __init__(self, stackList): self.stackList = stackList def push(self, topItem): self.stackList.append(topItem) print \'Item \', topItem, \' is pushed on the top of Stack.\' print \'The updated Stack is: \', self.stackList, \'\n\' def popvalue(self): if findPop() == True: topItem = self.stackList.pop() print \'Item \', topItem, \' has been poped.\' print \'The updated Stack is: \', self.stackList, \'\n\' else: topItem = self.stackList.pop[-1] print \'Item \', topItem, \' has been poped.\' self.stackList = self.stackList[:-2] print \'The updated Stack is: \', self.stackList, \'\n\' def isempty(self): if len(self.stackList) == 0: return True else: return False def peek(self): return self.stackList[-1] def findPop(): result = False for item in dir(list): if item == \'pop\': result = True break return result a_stack = StackPattern([1, 2, 3, 4, 5, 6, 7, 8]) a_stack.push(9) a_stack.popvalue() print \'Is Empty Value: \', a_stack.isempty() print \'Peek value\', a_stack.peek()
【执行结果】
Item 9 is pushed on the top of Stack.
The updated Stack is: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Item 9 has been poped.
The updated Stack is: [1, 2, 3, 4, 5, 6, 7, 8]
Is Empty Value False
Peek value 8
13-9.
队列类。一个队列(queue)是一种具有先进先出(first-in-first-out,FIFO)特性的数据结构。一个队列就像是一行队伍,数据从前端被移除,从后端被加入。博主:这有点像等待服务的银行客户,先来的先服务,后面还有新来的加到队伍尾巴。这个类必须支持下面几种方法:
enqueue()在列表的尾部加入一个新的元素。dequeue()在列表的头部取出一个元素,返回它并且把它从列表中删除。请参见上面的练习和示例6.3。
【注】
题目中用于队列的列表,list[0]是队首,list[-1]是队尾。
【答案】
代码如下:
#-*- encoding: utf-8 -*- class QueuePattern(object): \'定义队列模型类\' def __init__(self, queueList): self.queueList = queueList def enqueue(self, endItem): self.queueList.append(endItem) print \'Item \', endItem, \' is added at the end of Queue.\' print \'The updated Queue is: \', self.queueList, \'\n\' def dequeue(self): headItem = self.queueList[0] print \'Item \', headItem, \' has been deleted.\' self.queueList = self.queueList[1:] print \'The updated Queue is: \', self.queueList, \'\n\' a_queue = QueuePattern([1, 2, 3, 4, 5, 6, 7, 8]) a_queue.enqueue(9) a_queue.dequeue()
【执行结果】
Item 9 is added at the end of Queue.
The updated Queue is: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Item 1 has been deleted.
The updated Queue is: [2, 3, 4, 5, 6, 7, 8, 9]