Python:密谋约瑟夫斯

2024-05-15 12:11:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过Python实现一个解决Josephus问题的方法。By certain references I came to this code

def josephus(list, k):
    # pop automatically skips the dead guy
    i = k
    while len(list) > 1:
        print(list.pop(i)) # kill prisoner at i
        i = (i + k) % len(list)
    print('Survivor: ', list[0])

测试list=[1,2,3,4,5,6]和k=1的代码:

^{pr2}$

控制台生成输出:

2
4
6
3
1
Survivor:  5

所以我怎么能画出约瑟夫问题来显示每轮有哪些参与者死亡。最后,只有幸存者会留下来。我想这个实现可以遵循以下风格:

n=12的圆形图解中的约瑟夫问题:

enter image description here


Tags: to方法bylendefcodethispop