About Josephus_problem

I am trying to solve Josephus problem and I have working code.

def J(n,x): li=range(1,n+1) k = -1 while li: print li k = (k+x) % len(li) li.pop(k) k =k- 1 J(10, 3) 

Now I want to rewrite it to get the result as follows:

 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 1 1 0 1 1 1 1 1 1 0 1 1 0 1 1 0 1 1 0 0 1 1 0 1 1 0 1 1 0 0 1 1 0 0 1 0 1 0 0 0 1 1 0 0 1 0 1 0 0 0 1 1 0 0 0 0 1 0 0 0 1 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 

How can i do this?

 def J(n,x): li=[1]*10 k = -1 while li.count(1)>0: print li k = (k+x) % len(li) li[k]=0 k =k- 1 
+4
source share
1 answer
 >>> def J(n,x): li=range(1,n+1) k = -1 while li: for i in xrange(1,n+1): if i in li: print 1, else: print 0, print k = (k+x) % len(li) li.pop(k) k =k- 1 >>> J(10, 3) 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 1 1 0 1 1 1 1 1 1 0 1 1 0 1 1 0 1 1 0 0 1 1 0 1 1 0 1 1 0 0 1 1 0 0 1 0 1 0 0 0 1 1 0 0 1 0 1 0 0 0 1 1 0 0 0 0 1 0 0 0 1 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 

Even better (single-line replacing your print li ):

 >>> def J(n,x): li=range(1,n+1) k = -1 while li: print [1 if i in li else 0 for i in xrange(1,n+1)] k = (k+x) % len(li) li.pop(k) k =k- 1 >>> J(10, 3) [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] [1, 1, 0, 1, 1, 1, 1, 1, 1, 1] [1, 1, 0, 1, 1, 0, 1, 1, 1, 1] [1, 1, 0, 1, 1, 0, 1, 1, 0, 1] [1, 0, 0, 1, 1, 0, 1, 1, 0, 1] [1, 0, 0, 1, 1, 0, 0, 1, 0, 1] [0, 0, 0, 1, 1, 0, 0, 1, 0, 1] [0, 0, 0, 1, 1, 0, 0, 0, 0, 1] [0, 0, 0, 1, 0, 0, 0, 0, 0, 1] [0, 0, 0, 1, 0, 0, 0, 0, 0, 0] 

You can even use print ' '.join(['1' if i in li else '0' for i in xrange(1,n+1)]) to get the desired result :-)

+5
source

Source: https://habr.com/ru/post/1434866/


All Articles