刚开始学python——数据结构——“自定义队列结构“

时间:2023-03-09 18:04:36
刚开始学python——数据结构——“自定义队列结构“

自定义队列结构  (学习队列后,自己的码)

主要功能:用列表模拟队列结构,考虑了入队,出队,判断队列是否为空,是否已满以及改变队列大小等基本操作。

下面是封装的一个类,把代码保存在myQueue.py文件中(我保存在” C:/Users/Administrator/Desktop/时间宝/python/myQueue.py“中)。

 class myQueue:  #构造函数,默认队列大小10
def __init__(self,size=10):
self._content=[]
self._size=size
self._current=0 def setSize(self,size):
if size<self._current: #如果缩小队列,应删除后面的元素
for i in range(size,self._current)[::-1]:
del self._content[i]
self._current=size
self._size=size def put(self,v): #入队
if self._current<self._size:
self._content.append(v)
self._current=self._current+1
else:
print('The queue is full') def get(self): #出队
if self._content:
self._current=self._current-1
return self._content.pop(0)
else:
print('The queue is empty') def show(self): #显示所有元素
if self._content:
print(self._content)
else:
print('The queue is empty') def empty(self):
self._content=[] def isEmpty(self): #判断是否已满
if not self._content:
return True
else:
return False def isFull(self): #判断是否为空
if self._current==self._size:
return True
else:
return False if __name__=='__main__':
50 print('Please use me as a module.')

下面是演示自定义队列类的用法:

 ======= RESTART: C:/Users/Administrator/Desktop/时间宝/python/myQueue.py =======
Please use me as a module.
>>> import myQueue
>>> q=myQueue.myQueue()
>>> q.get()
The queue is empty
>>> q.put(5)
>>> q.put(7)
>>> q.idFull()
>>> q.isFull()
False
>>> q.put('a')
>>> q.put(3)
>>> q.show()
[5, 7, 'a', 3]
>>> q.setSize(3)
>>> q.show()
[5, 7, 'a']
>>> q.put(10)
The queue is full >>> q.setSize(5)
>>> q.put(10)
>>> q.show()
[5, 7, 'a', 10]

有个小问题就是“if __name__=='__main__':
                                 print('Please use me as a module.') “这个是什么意思,请大家给予答案!

以上就是这些,希望有所收获,再接再励。

相关文章