约瑟夫环问题

约瑟夫环:
30个人(15个教徒和15个非教徒)坐船出海 船坏 需要把15个人扔到海里 其他人才能幸存 围成一圈从某人开始从1报数 报到9的人 扔到海里 下一个人继续从1开始报数 直到扔掉15个人 结果由于神仙的保佑 15个教徒全部幸存 问最开始怎么站的

方法一

def joseph(total, begins, count):
    #total总人数30 ,begins编号1,count报数9

    queue = list(range(1, total + 1))
    
    death = (begins + count - 2) % len(queue)
    
    
    for times in range(total):
        if times ==15:
            break
        print ('out: ',queue[death])
        del queue[death]
        
        death = (death + count -1) % len(queue)
        
    print (queue)
joseph(30,1,9)

方法一打印结果

out是出局的, 列表里面的数字是存活下来的


约瑟夫环问题_第1张图片
07.png

方法二

def main():
    persons = [True]*30  #生成一个30个True的列表
    index = 0    #从0开始报数 每次index加1 当number等于9时,这个人就死了通过下标把
#这个人的列表值改成False,counter就加1 一直加到15 找出15个人跳出循环

    number = 0 
    counter = 0
    while counter<15:
        if persons[index]:
            number += 1

            if number ==9:
                persons[index] =False
                counter += 1
                number =0
        index += 1
        index %= len(persons)

    for person in persons:
        print('活'if person else"死",end='')

main()

你可能感兴趣的:(约瑟夫环问题)