山东智趣岛论坛

标题: 约瑟夫问题 [打印本页]

作者: liuyichen99    时间: 2024-7-9 14:24
标题: 约瑟夫问题
def josephus(n, m):
    # 初始化一个循环队列
    circle = [i for i in range(1, n+1)]
    # 用来追踪循环队列中的位置
    current_index = 0

    while len(circle) > 1:
        # 当前要出列的人员索引
        out_index = (current_index + m - 1) % len(circle)

        print(circle[out_index])
        # 将要出列的人员移除
        _ = circle.pop(out_index)
        # 更新当前索引位置
        current_index = out_index

    # 返回最后一个人员,即获胜者
    #return circle[0]

# 使用函数
winner = josephus(8, 5)
print(f"The winner is {winner}!")






欢迎光临 山东智趣岛论坛 (https://abc.sdzqd.com/) Powered by Discuz! X3.3