1. Operation principle of analog stack 
First in, then out
​1. initialization ( Create a list of stored data )
2. Use the list to save data
​ 3. Out of the stack Use lists to delete data
​ 4. Look at the top of the stack elements Slice to get the last bit of the list
​5. Judge whether it is an empty stack
6. The length of the stack

Program
stack=[]
info="""
******** Stack operation ******
1. Push
2. Out of the stack
3. Top element of stack
4. The length of the stack
5. Is the stack empty
"""
while True:
print(info)
choice=input("please input your choice:")
if choice=='1':
item=input(' Please enter the stack element :')
stack.append(item)
print('%s Stack successfully !'%item)
elif choice=='2':
if not stack:
print(' The stack is empty. , Cannot stack !')
else:
item=stack.pop()
print('%s Stack out successfully !'%item)
elif choice=='3':
if len(stack)==0:
print(' The stack is empty. !')
else:
print(' The element at the top of the stack is :%s'%stack[-1])
elif choice=='4':
print(' The length of the stack is %s'%len(stack))
elif choice=='5':
if len(stack)==0:
print(' The stack is empty. !')
else:
print(' Stack is not empty. !')
elif choice=='q':
print('logout')
break
else:
print('Error:check your input!')

Output results :

******** Stack operation ******
1. Push
2. Out of the stack
3. Top element of stack
4. The length of the stack
5. Is the stack empty please input your choice:1
Please enter the stack element :2
2 Stack successfully ! ******** Stack operation ******
1. Push
2. Out of the stack
3. Top element of stack
4. The length of the stack
5. Is the stack empty please input your choice:

2. furniture 

1. There are different types of houses , List of total area and furniture names , The new house doesn't have any furniture
2. The furniture has a name and an area , among 
The bed : Occupy 4 Square meters
Wardrobe : Occupy 2 Plane
table : Occupy 1.5 Square meters
3. Add these three pieces of furniture to the house
4. When you print the house , Request output : House type , Total area , The remaining area , List of furniture names
analysis :
1. Because of putting furniture in the house , So you need to create furniture class first
2. Furniture :
(1) attribute : name (name), Covers an area of (area)
(2) object : The bed (bed), Wardrobe (closet), table (table) 3. Houses :
(1) attribute : House type (house_style), Total area (zarea),
List of furniture names (namelist) ( The new house doesn't have any furniture , The initial furniture name list is empty surface )
The remaining area (farea) ( Because when printing houses , Request output ' The remaining area ', So the remaining area is the house The implied property of )
(2) Method : Add furniture (add_item)
class HouseItem:
def __init__(self, name, area):
self.name = name
self.area = area
def __str__(self):
return "[%s] Covers an area of %.2f" % (self.name, self.area) class House:
def __init__(self, house_type, area):
self.house_type = house_type
self.area = area
self.free_area = area
self.item_list = []
def __str__(self):
# python Can automatically connect the code inside a pair of brackets together
return (" House type : %s\n Total area : %.2f[ The remaining : %.2f]\n furniture :%s"
%(self.house_type, self.area,
self.free_area, self.item_list))
def add_item(self, item):
print(" You want to add %s" % item)
if item.area > self.free_area:
print("%s It's too big , Unable to add " % item.name)
return
self.item_list.append(item.name)
self.free_area -= item.area bed = HouseItem(" The bed ", 4)
chest = HouseItem(" Wardrobe ", 2)
table = HouseItem(" table ", 1.5)
print(bed)
print(chest)
print(table) my_home = House(" two bedrooms ", 60)
my_home.add_item(bed)
my_home.add_item(chest)
my_home.add_item(table)
print(my_home)

3.
​ 1. Soldier Ryan has one AK47
​ 2. Soldiers can fire ( The soldiers fired and pulled the trigger )
​ 3. gun can bullets ( Shoot the bullet out )
​ 4. gun can Loading bullets -- Increase the number of bullets
​ Soldier Gun
------------- -----------------
​ name model
​ gun bullet_count # There are enough bullets to complete the shooting
------------- -----------------
​ __init__(self): __init__(self):
​ fire(self): add_bullet(self,count):# Loaded with bullets
​ shoot(self): analysis :
1. Because soldier Ryan has one AK47, Soldiers can fire . So you need to create a gun class first 2. Guns (Gun):
(1) attribute : model (model), The number of bullets (bullet_count)
(2) Method : bullets (shoot), Loading bullets (add_bullet) 3. Soldiers (Soldier)
(1) attribute : full name (name), Gun name (Gun)
(2) Method : FireStarter (fire)

class Gun: #Gun gun 
def __init__(self, model):
self.model = model
self.bullet_count = 0
def add_bullet(self, count):
self.bullet_count += count
def shoot(self):
if self.bullet_count <= 0:
print("[%s There are no more bullets ..." % self.model)
return
self.bullet_count -= 1
print("[%s] A sudden outburst ...[%d]" % (self.model, self.bullet_count)) class Soldier:
def __init__(self,name):
self.name = name
self.Gun = Gun
def fire(self):
if self.Gun is None:
print("[%s] And guns ..." % self.name)
return
print(" Go ahead, cannon fodder ...[%s]" % self.name)
self.Gun.add_bullet(50)
self.Gun.shoot() AK47 = Gun("AK47")
xusandou = Soldier(" rank-and-file soldiers ")
xusandou.Gun = AK47
xusandou.fire()
print(xusandou.Gun)
 

Python More articles on object-oriented exercises

  1. python Advanced object-oriented built-in method

    One isinstance(obj,cls) and issubclass(sub,super) 1.1,isinstance(obj,cls) Check whether the obj Is it a class cls The object of class Foo(obj ...

  2. python Object oriented

    Python object-oriented ( Elementary chapter ) summary Process oriented : Write base code from top to bottom according to business logic Functional expression : Encapsulate a function code into a function , No need to write again in the future , Just call the function object-oriented : Classify and encapsulate functions , Let's develop " ...

  3. Python object-oriented Basics

    An overview of programming paradigms : Process oriented and object-oriented And functional programming Process oriented :(Procedure Oriented) It's an event centric programming idea . Is to analyze the steps needed to solve the problem , Then use functions to implement these steps step by step ...

  4. python Object-oriented progression ( 8、 ... and )

    Last one <Python Object oriented Elementary ( 7、 ... and )> This paper introduces the basic knowledge of object-oriented : Object oriented is a way of programming , The implementation of this programming method is based on   class   and   object   Use class It's a template , There are several packages in the template “ function ” For the sake of ...

  5. python object-oriented ( Advanced )

    Last one <Python object-oriented ( Elementary chapter )> This paper introduces the basic knowledge of object-oriented : Object oriented is a way of programming , The implementation of this programming method is based on class and object Use class It's a template , There are several packages in the template “ function ” For the sake of ...

  6. python Object oriented programming learning

    1. problem : Put all the code in one py file : Unable to maintain programme : If you divide the code into multiple py file , benefits : 1. Variables with the same name do not affect each other 2. Easy to maintain 3. Refer to the module : import module 2. package : solve ...

  7. Python Object oriented explanation

    Python Object oriented " Where there is pity " Python My hospitality -- Who can come in Python Encapsulation -- Just give you what you want Python Inheritance -- I know Godfather everywhere Python The polymorphism of -- Say yes.

  8. python Object oriented and class membership and exception handling

    python object-oriented You think of yourself as a God , You're going to create a planet , First of all, you have to knead it into balls , Two diameters can create a ball class star: ''' name (name), The equatorial diameter (equatorial di ...

  9. python Introductory exercises 1

    common python Introductory exercises 1. perform python Two ways of scripting The first one is : to python Script an executable permission , Go to current storage python Directory of programs , Give me a x Executable rights , Such as : There is one homework.py writing ...

  10. python Object oriented learning

    ------Python Object oriented Write a simple and practical class below , In order to understand the class easily #python 3.5 Environmental Science , The interpreter is in linux Need to change # Read the manual and check readme file # author :S12- Chen Jinpeng class ...

Random recommendation

  1. Javascript First chapter _8( event )

    event HTML The incident happened in HTML Things on the element . For example, when a user clicks a button , Clicking is also an event . Events can be used to process form validation , User input , User behavior and browser action , Such as : Event triggered on page load Event triggered when the page is closed user ...

  2. Commonly used C# Keyword tutorial

    Many students in the background of the learning website are right C# Some of the key words are not clear , Now let's learn the meaning of these keywords type Void  When used as the return type of a method ,void Keyword specifies that the method does not return a value . ... is not allowed in the parameter list of a method ...

  3. java URL Call other systems to send messages and get the returned data

    Simulation of the system through Url Send the message to the target server , And get the return data :( Implementation class ) import java.io.BufferedOutputStream; import java.io.BufferedRea ...

  4. AC Diary —— Upper and lower case letters are interchanged openjudge 1.7 14

    14: Upper and lower case letters are interchanged Total time limit :  1000ms Memory limit :  65536kB describe Replace all uppercase letters in a string with lowercase letters , At the same time, replace lower case letters with upper case letters . Input The input line : The string to be exchanged ...

  5. Ubuntu Build in LAMP And php development tool

    So-called LAMP, refer to :Linux+Apache+Mysql+Php Just make a memo here Step1. install Apache 1. stay terminal Enter a command in and execute : sudo apt-ge ...

  6. hadoop Of RPC signal communication

    RPC(remote procedure call) The remote invocation Different Java Object method calls between processes One side is called the server (server), One side is called the client (client) server The end provides the object , For the client to call , ...

  7. Visual Studio Shortcut key settings

    1. View the current shortcut : Environmental Science - keyboard - Press shortcut key 2. Text editor -C#- Show - Line number 3. Text editor -C#- tabs - Insert space 4. Text editor - All languages - Apply the cut or copy command to empty lines when there is no selection 5.Ctrl+Shift- ...

  8. unity3D It's a mixture of coroutines and threads

    This is me google unity3D A problem happened to be stackflow Very interesting post on : The main idea is To be in unity3D From server Download a zip, And unzip to the persistent address . And load it into memory . The following shows ...

  9. cygwin vi Editor left and right up and down key and delete key garbled error

    install cygwin Then use one of the vi Editor found up and down around the key and delete key garbled , Search the Chinese help program , No solution , Finally, I searched English websites , Found a solution . The reference link is as follows :http://superuser.com/que ...

  10. luogu【P2745】[USACO5.3] Window area Window Area

    This question It's an engineering problem ( But at first I didn't know how to do it .. Let's see nocow Of ..qwq)( The entrance to the original question ) Algorithm for discretization + Scan line   Make the big coordinates smaller   also Scan with the horizontal and vertical coordinates To calculate the area In limine I want to add ...