Python core programming version 2, 407th page, Chapter 4 exercises continued 5-answers to Python core programming-self-developed-

Source: Internet
Author: User

This is a self-made exercise and may be incorrect. You are welcome to discuss and discuss various optimization and reconstruction solutions.
Based on feedback or code review, the updated answers or related content of this article will be added to the comments of this blog.
We will try to ensure that the answer code for each question is complete, not just functions or classes. Open the Python 2.7 IDLE and copy the complete code to debug and run it.
Welcome to Balian's blog home. Http://www.cnblogs.com/balian

13-8.
Stack class. A stack is a data structure with the last-in-first-out (LIFO) feature. We can think of it as a dining tray. The first dish is the last one, and the last one is the first one. Blogger: This is a bit like a bullet clip. The first bullet to be pressed is shot at the end. Your class should have the push () method (medium-pressure data entry into the stack) and pop () method (remove a data item from the stack ). There is also a Boolean method called isempty. If the stack is empty, a Boolean value of 1 is returned; otherwise, 0 is returned. A method named peek () retrieves the data item at the top of the stack, but does not remove it.
Note: If you use a list to implement the stack, the pop () method already exists from Python1.5.2. Add a piece of code in your new class to check whether the pop () method already exists. If the pop () method has been checked, call this built-in method; otherwise, execute the pop () method you have compiled. You may need to use a list object. If you want to use it, you do not need to worry about implementing the list function (such as slicing ). You only need to ensure that the Stack class you write can correctly implement the above two functions. You can use the subclass of the list object or write a list-like object by yourself. See example 6.2.

[Note]
The 142 page of the book mentions how to check built-in functions of the list type. The blogger uses Python 2.7 to find the pop () method.

Microsoft Windows [Version 6.1.7601]Copyright (c) 2009 Microsoft Corporation.  All rights reserved.C:\>pythonPython 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32Type "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']

A short program can be used to check whether "pop" exists in the output result (actually a list) of dir (list ":

def findPop():    result = False    for i in dir(list):        if i == 'pop':            result = True            break    return result

In addition, for the stack list, list [0] is the bottom of the stack, and list [-1] is the top of the stack.

[Answer]

The Code is as follows:

#-*-Encoding: UTF-8-*-class StackPattern (object): 'defines the stack model class' 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 ()

[Execution result]

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 class. A queue is a data structure with the first-in-first-out (FIFO) feature. A queue is like a queue. Data is removed from the front end and added from the back end. Blogger: This is a bit like a bank customer waiting for service, serving first, followed by a new addition to the team's tail. This class must support the following methods:

Enqueue () adds a new element to the end of the list. Dequeue () extracts an element from the header of the list, returns it, and deletes it from the list. See the exercise and example 6.3 above.

[Note]

The list used for the queue in the question. list [0] is the first team, and list [-1] is the end of the team.

[Answer]

The Code is as follows:

#-*-Encoding: UTF-8-*-class QueuePattern (object): 'defines the queue model class '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 ()

 


[Execution result]

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]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.