"Monkey choose King" algorithm python implementation

Source: Internet
Author: User
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

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.