这是自己做的练习,可能有错误,欢迎讨论和各种优化重构方案。
根据反馈,或者code review,对本篇文章答案或者相关内容的更新补充,一般会被添加在本篇博客的评论中。
将尽量保证每题的答案代码是完整的,不仅仅是函数或者类,打开Python 2.7的IDLE,将代码完整拷贝进去,就能调试运行。
欢迎访问Balian在博客园的家。 http://www.cnblogs.com/balian

13-10.
堆栈和队列。编写一个类,定义一个能够同时具有堆栈()和队列()操作行为的数据结构。这个类和Perl语言中的数组相像。需要实现四个方法:
shift()    返回并删除列表中的第一个元素,类似于前面的dequeue()函数。
unshift() 在列表的头部“压入”一个新元素。
push() 在列表的尾部加上一个新元素,类似于前面的enqueue()和push()方法。
pop() 返回并删除列表中的最后一个元素,与前面的pop()方法完全一样。
请参见练习13-8和练习13-9。

【答案】
代码如下:

#-*- encoding: utf-8 -*-

class ArrayPattern(object):
    '定义数组模型类'
    
    def __init__(self, arrayList):
        self.arrayList = arrayList
        
    def shift(self):
        headItem = self.arrayList[0]
        print 'Item ', headItem, ' is deleted from the head of array.'
        self.arrayList = self.arrayList[1:]
        print 'The updated array is: ', self.arrayList, '\n'
        
    def unshift(self, headItem):
        tempList = [headItem]
        for item in self.arrayList:
            tempList.append(item)
        self.arrayList = tempList
        print 'Item ', headItem, ' is added on the head of array'
        print 'The updated array is: ', self.arrayList, '\n'  
       
    def push(self, endItem):
        self.arrayList.append(endItem)
        print 'Item ', endItem, ' is added on the end of array.'
        print 'The updated array is: ', self.arrayList, '\n'     
    
    def pop(self):
        endItem = self.arrayList.pop()
        print 'Item ', endItem, ' is poped.'
        print 'The updated array is: ', self.arrayList, '\n'    
          
            
a_array = ArrayPattern([1, 2, 3, 4, 5, 6, 7, 8])
a_array.shift()
a_array.unshift(9)
a_array.push(10)
a_array.pop()
 
【执行结果】

Item  1  is deleted from the head of array.
The updated array is:  [2, 3, 4, 5, 6, 7, 8]

Item  9  is added on the head of array
The updated array is:  [9, 2, 3, 4, 5, 6, 7, 8]

Item  10  is added on the end of array.
The updated array is:  [9, 2, 3, 4, 5, 6, 7, 8, 10]

Item  10  is poped.
The updated array is:  [9, 2, 3, 4, 5, 6, 7, 8]


13-11.
电子商务。
你需要为一家B2C(企业到消费者)零售商编写一个基础的电子商务引擎。你需要写一个针对顾客的类User,一个对应存货清单的类Item,还有一个对应购物车的类叫Cart。货物放到购物车里,顾客可以有多个购物车。同时购物车里可以有多个货物,包括多个同样的货物。
【未完】
感觉有难度,暂时押后。

13-12.
聊天室。
因为博客只讨论技术,所以题目略有修改,原题请见书第408页。创建一个新的聊天室。你需要三个类:一个Message类,它包含一个消息字符串以及诸如广播、单方收件人等其他信息;一个User类,包含了进入你聊天室的某个人的所有信息。还有一个Room类,它体现了一个更加复杂的聊天系统,用户可以在聊天时创建单独的“房间”,并邀请其他人加入。附加题:请为用户开发一个图形化用户界面应用程序。
【未完】
感觉有难度,暂时押后。

posted on 2012-09-21 11:12  balian  阅读(1023)  评论(0编辑  收藏  举报