gpt4 book ai didi

python - 关于 Josephus_problem

转载 作者:太空狗 更新时间:2023-10-30 02:48:31 25 4
gpt4 key购买 nike

我正在尝试解决 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

最佳答案

>>> 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)]) 得到准确的输出你想要:-)

关于python - 关于 Josephus_problem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12479282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com