The python algorithm "Monkey King election" is implemented today to implement a Joseph ring algorithm. The following is a Sina interview question:
M monkeys sat in a circle and numbered from 1 to m clockwise. Then, the number of monkeys starting from 1 clockwise starts to report to n's monkeys, and then starts reporting again from the next position of the first monkey, it is king. Design and write programs to implement the following functions:
(1) the number of monkeys at the start of user input is required.
(2) give the initial number of the Monkey King.
This is a typical Joseph's ring problem.
Note: This instance is tested in python2.7 and not in python3. if you are interested, you can contact the group.
Directly run the code:
#! /Usr/bin/python # coding = UTF-8 # The Monkey king issue of the Joseph ring algorithm def king (m, n ): dd ={}# generate a dictionary p = 1 while (p <= m): dd [p] = p + 1 j = 1 while (len (dd)> 1): for k, v in dd. items (): if (j = n): del dd [k] j = 1 else: j = j + 1 return dd print king (6, 2)
Note: The dictionary is used here, instead of list. This is mainly because the advantages of Dictionary indexes can be used.