【发布时间】:2018-07-23 14:19:19
【问题描述】:
我的朋友告诉我Josephus problem,你有41 的人坐在圈子里。人号1有剑,杀了右边的人,把剑传给下一个人。这种情况一直持续到只剩下一个人活着。我在 python 中提出了这个解决方案:
print('''There are n people in the circle. You give the knife to one of
them, he stabs person on the right and
gives the knife to the next person. What will be the number of whoever
will be left alive?''')
pplList = []
numOfPeople = int(input('How many people are there in the circle?'))
for i in range(1, (numOfPeople + 1)):
pplList.append(i)
print(pplList)
while len(pplList) > 1:
for i in pplList:
if i % 2 == 0:
del pplList[::i]
print(f'The number of person which survived is {pplList[0]+1}')
break
但它只适用于 42 人。我应该怎么做,或者我应该如何更改代码以使其适用于例如100, 1000 和圈子中的更多人?
我查看了约瑟夫斯问题并看到了不同的解决方案,但我很好奇我的答案在经过一些小的调整后是否正确,或者我应该从头开始。
【问题讨论】:
-
阅读ericlippert.com/2014/03/05/how-to-debug-small-programs 了解有关如何调试代码的一些提示。
-
最多只能容纳 42 人是什么意思?当你尝试 43 或更多时会出现什么错误?
-
那么答案是错误的。我不知道如何写 i % 2 != 0 的条件
-
如果您单击 Josephus 标签,您将看到带有该标签的所有问题。你会发现许多不同的方法来解决这个问题(以及相关的问题,你不仅想知道谁幸存下来,还想知道受害者的名单按照他们被杀的顺序)。