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.