Cool Python, simple 10 lines of code to solve Joseph ring

Source: Internet
Author: User

Joseph Ring (Josephson problem) is a mathematical application problem: Known n individuals (numbered 1,2,3...N respectively) sits around a round table. From the number of people numbered K, count to M the man out of the column, his next person from 1 start off, Count to M of the person again out, according to this rule repeat, until the round table around the people all out. Usually when solving such problems, we put the number from 0~n-1, and the final result +1 is the solution of the original problem.

Although the efficiency of solving the Joseph ring problem with simulations is very low, it is much easier to understand. First the code.

The code is as follows Copy Code


def Josephus (N,k):
Link=range (1,n+1)
Ind=0
For loop_i in range (n-1):
IND = (ind+k)% len (link)
Ind-=1
print ' Kill: ', Link[ind]
Del Link[ind]
If Ind==-1: # The last element of link
Ind=0
print ' Survice: ', link[0]


if __name__ = = ' __main__ ':

Josephus (100000,300)
print '-' *30
Josephus (10,5)
print '-' *30
Josephus (10,1)

As you can see, the entire function is just 10 lines. The idea is very simple, according to die to find the location to delete, but, mainly to subscript starting from 0 and the number starting from 1 is somewhat different, in addition, Py del, the next RCAs 1, so to reduce back.


Right look is
Del Link[ind-1]
Ind-=1
But, because both need to back 1, so direct ind-=1 is OK.
In addition to the main, came to the end of the ring, that is, py 1 (This is the best place, py tuple and list support negative subscript), deleted, the beginning will become 0


If you think I'm wrong, you must comment to me, do not want to fraught.

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.