什么是队列
队列是线性的集合,对于队列来说,插入限制在一端(队尾),删除限制在另一端(队头)。队列支持先进先出(FIFO)的协议。
队列的实现
class Queue:
def __init__(self):
self.__items = []
def is_empty(self):
return self.__items == []
def peek(self):
if not self.is_empty():
return self.__items[-1]
return None
def enqueue(self, item):
self.__items.insert(0, item)
def dequeue(self):
if not self.is_empty():
return self.__items.pop()
return None
def size(self):
return len(self.__items)
队列的应用
约瑟夫环问题的实现
问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到k的那个人被杀掉;他的下一个人又从1开始报数,数到k的那个人又被杀掉;依此规律重复下去,直到圆桌周围的人只剩最后一个。
思路:将参与这个事件的所有的人名列表加入到队列,然后从第一个人开始报数,报数的过程就是一次出队列和再进队列的一个过程,报到K的那个人出列,被杀掉(不再进队列),然后继续由下一个开始报数,循序往复,最后队列中所剩下的人就是幸存者。
from queue import Queue
def josephus(name_list, num):
simqueue = Queue()
for name in name_list:
simqueue.enqueue(name)
while simqueue.size() > 1:
for i in range(1, num + 1):
simqueue.enqueue(simqueue.dequeue())
simqueue.dequeue()
return simqueue.dequeue()
if __name__ == "__main__":
print("The survivor is %s" % josephus(['steve','jobs', 'bill', 'gates', 'trump', 'obama', 'pepepao', 'pages', 'maske', 'cook'], 4))
运行程序,打印输出如下结果:
>>> The survivor is bill
打印机设置调优问题
问题描述:一个实验室,再任意一个小时内,大约有10名学生在场,这一小时中,每人会发起2次左右的打印,每次1~20页。打印机的性能是:1、以草稿模式打印的话,每分钟10页。2、以正常的方式打印的话,打印质量好,但速度下降为每分钟5页。
思路:对问题进行建模
1、确定生成概率:实例为每小时会有10个学生提交的20个作业,这样,概率就是每180秒会有1个作业生成并提交,概率为每秒1/180
2、确定打印页数: 实例是120页,那么就是120页之间的概率相同
import random
import time
from queue import Queue
class Printer:
def __init__(self, print_per_minute):
self.__pagirate = print_per_minute
self.__current_task = None
self.__remain_time = 0
def tick(self):
if self.__current_task != None:
self.__remain_time = self.__remain_time - 1
if self.__remain_time <= 0:
self.__current_task = None
def busy(self):
return self.__current_task != None
def start_next(self, new_task):
self.__current_task = new_task
self.__remain_time = new_task.get_pages() * 60 / self.__pagirate
class Task:
def __init__(self, time):
self.__time = time
self.__pages = random.randrange(1, 21)
def get_pages(self):
return self.__pages
def get_timestamp(self):
return self.__time
def wait_time(self, current_time):
return current_time - self.__time
def new_print_task():
num = random.randrange(1, 181)
return num == 180
def simulate(simulate_seconds, page_per_minute):
printer = Printer(page_per_minute)
task_queue = Queue()
wait_time_list = []
for current_second in range(simulate_seconds):
if new_print_task():
task = Task(current_second)
task_queue.enqueue(task)
if (not printer.busy()) and (not task_queue.is_empty()):
next_task = task_queue.dequeue()
wait_time_list.append(next_task.wait_time(current_second))
printer.start_next(next_task)
printer.tick()
average_wait = sum(wait_time_list) / len(wait_time_list)
print("Average wait %6.2f secs %3d tasks remaining." % (average_wait, task_queue.size()))
if __name__ == "__main__":
print("=======================5 page in one minute==========================")
for i in range(10):
simulate(3600, 5)
print("=======================10 page in one minute==========================")
for i in range(10):
simulate(3600, 10)
运行程序,打印输出如下结果:
>>> =======================5 page in one minute==========================
Average wait 150.79 secs 0 tasks remaining.
Average wait 112.60 secs 0 tasks remaining.
Average wait 373.30 secs 7 tasks remaining.
Average wait 275.47 secs 1 tasks remaining.
Average wait 52.62 secs 0 tasks remaining.
Average wait 47.93 secs 4 tasks remaining.
Average wait 123.37 secs 3 tasks remaining.
Average wait 55.60 secs 2 tasks remaining.
Average wait 11.57 secs 0 tasks remaining.
Average wait 35.62 secs 0 tasks remaining.
=======================10 page in one minute==========================
Average wait 18.62 secs 0 tasks remaining.
Average wait 10.95 secs 0 tasks remaining.
Average wait 4.20 secs 0 tasks remaining.
Average wait 28.25 secs 0 tasks remaining.
Average wait 9.15 secs 0 tasks remaining.
Average wait 4.26 secs 0 tasks remaining.
Average wait 16.93 secs 0 tasks remaining.
Average wait 35.08 secs 0 tasks remaining.
Average wait 12.41 secs 0 tasks remaining.
Average wait 50.18 secs 0 tasks remaining.
通过两种模式各自模拟10次的打印结果,我们看到按正常模式设置,最多一次需要等待373秒,要等待6分钟左右,1个小时后还有7个任务没用完成。调成草稿模式后,最短只要等待4秒左右,模拟10次发现没有一次在一小时内没有完成所有打印任务的。所以我们想要提高打印效率,只能牺牲打印质量了。
双端队列
deque 即双端队列。是一种具有队列和栈的性质的数据结构。双端队列中的元素可以从两端弹出,也可以从两端加入。它并没有先天的FIFO和LIFO的特性。
双端队列的实现
class deque:
def __init__(self):
self.__items = []
def is_empty(self):
return self.__items == []
def add_near(self, item):
self.__items.insert(0, item)
def add_front(self, item):
self.__items.append(item)
def remove_near(self):
return self.__items.pop()
def remove_front(self):
return self.__items.pop(0)
def size(self):
return len(self.__items)
双端队列的实例
判断是否是回文字符串
思路:回文字符串的判定就是从左到右正着阅读文字和从右到左反着阅读文字其内容表达一致。用双端队列来判断回文字符串再合适不过了,先将带判定的字符串全部添加到双端队列中,然后再在双端队列的两端同时取出一个字符进行比较,如果一致就循序往复的进行取字符进行比较,直到队列中剩下0个或1个字符,如果有不一致的就返回False结束循环。
from queue import Deque
def check_palindrome(str_exp):
str_deque = Deque()
for i in range(len(str_exp)):
str_deque.add_near(str_exp[i])
still_ok = True
while str_deque.size() > 1 and still_ok:
str1 = str_deque.remove_near()
str2 = str_deque.remove_front()
if str1 != str2:
still_ok = False
return still_ok
if __name__ == "__main__":
print(check_palindrome("上海自来水来自海上"))
运行程序,并打印结果如下
>>> True