Python implementation of "Monkey King election" algorithm

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

Related Article

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.