代码:
1.节点类 (QueueNode.py)
class QueueNode(object):
def __init__(self,value,nxt,prev):#get 4 arguments
self.value=value
self.next=nxt
self.prev=prev
def __repr__(self):
pval=self.prev and self.prev.value or None
nval=self.next and self.next.value or None
return f"{self.value}:nval={repr(nval)},pval={repr(pval)}"
2.队列类(Queue.py)
from QueueNode import *
class Queue(object):
def __init__(self):
self.head=None
self.tail=None
def shift(self,obj):#stand the back of Queue
"""Shifts a new element onto the back of the queue."""
if self.head:
node=QueueNode(obj,None,self.tail)
self.tail.next=node
self.tail=node#!!!
else:
node=QueueNode(obj,None,None)
self.head=node
self.tail=node
def unshift(self):#go out at the first positon
if self.head:
node=self.head #要放在这里 不然if的代码块无法return
if self.head==self.tail: #just one element
self.head=None
self.tail=None
else: #many
self.head=node.next#head.next?
self.head.prev=None
return node.value
else:
return None
def drop(self):
"""Take the tail item and forget about it."""
if self.head:
if self.head==self.tail:#single element
self.head=None
self.tail=None
else:
self.tail=self.tail.prev
self.tail.next=None
def first(self):
"""Returns a *reference* to the first item, does not remove."""
return self.head !=None and self.head.value or None
def empty(self):
"""Indicates if the Queue is empty."""
return self.head == None
def count(self):
"""Counts the number of elements in the queue."""
node=self.head
count=0
while node:#@!!!
count +=1
node=node.next
return count
def dump(self,mark="----"):
"""Debugging function that dumps the contents of the queue."""
node=self.head
print(mark,end="")
while node:#!!!!!!@@@
print(node,end="")
node=node.next
print()
3.自动化测试:
from Queue import *
from QueueNode import *
def test_shift():
colors = Queue()
colors.shift("Pthalo Blue")
assert colors.count() == 1
colors.shift("Ultramarine Blue")
assert colors.count() == 2
print("pass!")
def test_unshift():
colors = Queue()
colors.shift("Magenta")
colors.shift("Alizarin")
assert colors.unshift() == "Magenta"
assert colors.unshift() == "Alizarin"
assert colors.unshift() == None
def test_first():
colors = Queue()
colors.shift("Cadmium Red Light")
assert colors.first() == "Cadmium Red Light"
colors.shift("Hansa Yellow")
assert colors.first() == "Cadmium Red Light"
colors.shift("Pthalo Green")
assert colors.first() == "Cadmium Red Light"
def test_drop():
colors = Queue()
colors.shift("Cad Red")
colors.shift("Hansa Yellow")
assert colors.count() == 2
colors.drop()
assert colors.count() == 1
assert colors.first() == "Cad Red"
colors.drop()
assert colors.first() == None
我在test_xxx里放了个print()
这是上个文章ex14中我懒得用的pytest -xs
对于pytest呢:1.安装 pip intall pytest
2.使用 雷同nosetests 但是不用进入virtualenv
不用我们pushd popd ./.venvs/lpthw/Scripts/activate …etc
3.-xs 可以输出!!
take notes:
queue model:
shift()
unshft():
drop()
有人不想排队了,从后面走了
队尾变成前一个人
队尾后面是空的
总结:
队列判断空看头!! head=None