class Que:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def in_que(self, item):
self.items.insert(0, item)
def out_que(self):
return self.items.pop()
def size(self):
return len(self.items)
>>> q=Que()
>>> q.is_empty()
True
>>> q.in_que("py")
>>> q.in_que("java")
>>> q.out_que()
'py'
>>> q.size()
1
>>> q.out_que()
'java'
在这个游戏中,孩子们围成一圈,并依次尽可能快地传递一个土豆,在某个时刻,大家停止传递,此时手里有土豆的孩子就得退出游戏。
设队列中的第一个手里有土豆,传递到num次后停止 ,此时持有土豆的退出,最后只剩下一个
from pythonds.basic import Queue
def pass_the_potatoes(ls, num):
Q = Queue()
for item in ls:
Q.enqueue(item)
while Q.size() > 1:
for i in range(num):
Q.enqueue(Q.dequeue())
Q.dequeue()
return Q.dequeue()
>>> pass_the_potatoes(['a','b','c','d','e','f'],3)
'e'
>>> pass_the_potatoes(['a','b','c','d','e','f'],5)
'd'
>>> pass_the_potatoes(['a','b','c','d','e','f'],7)
'c'
前后端均可入队出队
class Deque:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def add_front(self, item):
self.items.append(item)
def add_rear(self, item):
self.items.insert(0, item)
def remove_front(self):
return self.items.pop()
def remove_rear(self):
return self.items.pop(0)
def size(self):
return len(self.items)
>>> dq=Deque()
>>> dq.add_front('a')
>>> dq.add_front('b')
>>> dq.size()
2
>>> dq.remove_front()
'b'
>>> dq.add_rear('c')
>>> dq.remove_front()
'a'
按从左往右的顺序将字符串中的字符添加到双端队列的后端
前后端相同移除前后端字符
from pythonds.basic import Deque
def check_palindrome(s):
dq = Deque()
for c in s:
dq.addRear(c)
f = True
while dq.size() > 1 and f:
head = dq.removeFront()
tail = dq.removeRear()
if head != tail:
f = False
return f
>>> check_palindrome("abba")
True
>>> check_palindrome("tootoot")
True
>>> check_palindrome("qwertyrewq")
False