用python实现约瑟夫环

先上代码:

def circle(number, k):
    length = number
    people = []
    for index in range(number):
        people.append(index + 1)
    j = 0
    temp = 0
    res = 0
    while number > 1:
        index = j % length
        if people[index] != 0:
            temp += 1
        if temp == k:
            people[index] = 0
            number -= 1
            temp = 0
        j += 1
    for index, i in enumerate(people):
        if i != 0:
            res = index + 1
            
    return res

    约瑟夫环指的是有number个人围着圈坐, 按1到number编号,从编号1开始报数,当报到k的时候该人自动退出,从下一个人开始重新报数,直到最后剩一个人,求此人的编号。

结果验证为:

print(circle(9,2))
3
print(circle(8,2))
1

猜你喜欢

转载自blog.csdn.net/manmanxiaowugun/article/details/79822963