V. Applications of the queue - a hot potato

Hot potato game: Siege of six children in a circle, specify the order of the children themselves. The first child of the hands of a hot potato, sweet potato will need timing 1 second timer is passed to the next child, and so on. Rule is that when the timer counting every 7 seconds, the hands of a potato kids out of the game. The rest of the game until the end of a child, the last remaining child wins. Please use the queue implementation strategy of the game, came in several locations will eventually win.

  - This game is equivalent to the famous Joseph problems, a well-known first century historian Josephus legend. The story is that he and his 39 comrades surrounded by the Roman army in the cave. They decided rather die, do not become a slave to the Romans. They formed a circle, one of whom is designated as the first person to report the number of clockwise seventh person, he will be killed. Josephus was a successful mathematician, he immediately came up where it should take in order to become the last man.

 

Analysis: To simulate this circle, we can use the queue. Assuming that the game starts, came in first in the queue (first team) in the hands of a child holding a potato. After the start of the game, holding the child out of the queue potato and re-entry queue, passing the potato to the next child. Whenever the hands of the potato to the team's first child, the child's first team, first-out queue re-entry queue, once on. After passing six times out of the hands of a potato kids, games continue, continue to pass potato.

 

复制代码
class Queue():
    def __init__(self):
        self.items = []
    def enqueue(self,item):
        self.items.insert(0,item)
    def isEmpty(self):
        return self.items == []
    def dequeue(self):
        if self.isEmpty():
            return ''
        else:
            return self.items.pop()
    def size(self):
        return len(self.items)
    def travel(self):
        print(self.items)

The most basic wording 1:

names = ['A','B','C','D','E','F']
q = Queue()
for name in names:
    q.enqueue(name)
# q.travel()
while q.size() > 1:
    for i in range(7):
#         q.travel()
        kid = q.dequeue()
        q.enqueue(kid)
    q.dequeue()
    
print(q.dequeue())

Writing function formula 2:

def hotPotato(namelist, num):
    simqueue = Queue()
    for name in namelist:
        simqueue.enqueue(name)

    while simqueue.size() > 1:
        for i in range(num):
            kid = simqueue.dequeue()
            simqueue.enqueue(kid)

        simqueue.dequeue()

    return simqueue.dequeue()

print(hotPotato(["Bill","David","Susan","Jane","Kent","Brad"],7))

 

Guess you like

Origin www.cnblogs.com/studybrother/p/11145147.html