10 line Python code to solve Joseph ring (analog)

Source: Internet
Author: User

I wrote this article because I saw someone else's blog with a long space (more than 50 lines) to solve a Joseph ring problem, but also for the simplicity of Python, and if you use X-degree search Python Joseph, see the first few are wrong, it is a good tragedy.

In general, it is fraught.

Although, using simulations to solve this Joseph ring problem is inefficient, but it's easier to understand.

First, the 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 rows.

The idea is very simple, according to the mode to find the location to delete, but, mainly to subscript starting from 0 and the number from 1 is some different, in addition, the Py del, the lower bidding clubs 1, so to reduce back.

Right look is

Del Link[ind-1]

Ind-=1

However, because both need to retreat 1, so the direct ind-=1 is OK.

In addition to the main is, to the end of the ring, that is, PY-1 (This is the best place, the PY tuple and list support negative subscript), after deletion, the beginning will become 0

If you think I'm wrong, be sure to comment to me and point out that you don't want to fraught.

10 line Python code to solve Joseph ring (analog)

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.