我正在尝试解决Josephus problem,并且我有工作代码。
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)
现在我想重写它以获得如下结果:
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
我该怎么做?
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
答案 0 :(得分:5)
>>> 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
更好(单行代替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]
您甚至可以使用print ' '.join(['1' if i in li else '0' for i in xrange(1,n+1)])
来获得所需的输出: - )