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:\Users\Sahara\.virtualenvs\untitled\Scripts\python.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

  

上一篇:js数组之从数组中删除元素


下一篇:Maven项目中的配置文件找不到以及打包问题