Today to implement a Joseph ring algorithm, the following is a Sina interview question:
M monkeys sit in a circle, numbering from 1 to m in a clockwise direction. Then from the 1th monkey began to count in the clockwise direction from 1, Report N of the monkey out, and then from the first out of the next position of the monkey to start a count, so repeat, until the left a monkey, it is the king. Design and write programs to achieve the following functions:
(1) required by the user to enter the beginning of the monkey number M, count the last number of N.
(2) Give the initial number of the chosen Monkey King.
This question is a typical Joseph ring problem, "The Monkey Choose King" problem.
Note: This example test passed under python2.7, not tested under Python3, interested students can communicate in the group
Directly on the code:
#!/usr/bin/python# coding=utf-8# Joseph Ring algorithm for the monkey to choose the king Problem def king (m,n): dd = {} #生成一个字典 p = 1 while (p<=m):
DD[P] = p 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 the list. This is mainly because of the advantages of using the index of the dictionary