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)