python--使用队列结构来模拟烫手山芋的游戏
Posted aguncn
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python--使用队列结构来模拟烫手山芋的游戏相关的知识,希望对你有一定的参考价值。
基本功,磨起来。
# coding = utf-8 class Queue: def __init__(self): self.items = [] def is_empty(self): return self.items == [] # 入队列,加在首部 def enqueue(self, item): self.items.insert(0, item) # 出队列,最后一个 def dequeue(self): return self.items.pop() def size(self): return len(self.items) def hot_potato(name_list, num): sim_queue = Queue() # 先建好队列 for name in name_list: sim_queue.enqueue(name) # 循环到队列里只有1人为止 while sim_queue.size() > 1: # 进出队列到指定数量 for i in range(num): sim_queue.enqueue(sim_queue.dequeue()) # 此时,出队列的,即为淘汰人员 del_name = sim_queue.dequeue() print(‘delete name is : ‘, del_name) return sim_queue.dequeue() names = [‘Amy‘, ‘Tom‘, ‘Mary‘, ‘Jack‘, ‘Andy‘, ‘Leo‘] number = 9 print(hot_potato(names, number))
输出:
C:UsersSahara.virtualenvsuntitledScriptspython.exe D:/test/python_queue.py delete name is : Jack delete name is : Mary delete name is : Leo delete name is : Amy delete name is : Andy Tom Process finished with exit code 0
以上是关于python--使用队列结构来模拟烫手山芋的游戏的主要内容,如果未能解决你的问题,请参考以下文章