Queue application of hot potato

Hot potato (Joseph problems)

Queue algorithm to achieve hot potato issue, a list of names to participate in the game, and the number of retransmissions potatoes num, the algorithm returns the last remaining names

from pythonds.basic.Queue import Queue

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

    while simqueue.size() > 1:
        for i in range(num):
            simqueue.enqueue(simqueue.dequeue())    #一次传递

        simqueue.dequeue()
    return simqueue.dequeue()
print(hotPotato(["Bill", "David", "Susan", "Jane", "Kent", "Brad"], 7))

Algorithms ideas:
First, there are n people into the team, and then loop through the implementation of a number of requests the team into the team, and required a loop is executed seven times, and then let people take the potatoes out of the first team squad, the remaining n-1 in individuals cycle seven times, back and forth so that the implementation of the last remaining person is the most winners
.

Through this example we find the queue can solve some of the cycle of operation, such as passing objects, such as the number of cycles reported a series of problems.

Published 25 original articles · won praise 3 · Views 473

Guess you like

Origin blog.csdn.net/qq_44045101/article/details/103211921