Python solves the problem of monkey choosing the king: 15 monkeys form a circle to choose the king, and the monkeys that report to 7 are eliminated, until the last monkey becomes the king. Question: Which monkey will become the king?

Not much to say, super simple, just go to the code:

## 给猴子编号
AllMonkey = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

## 循环出栈
num = 0 #只要是为了清楚显示当前循环是第n次循环
while True:
    for i in range(1,7):
        AllMonkey.append(AllMonkey[0]) #第一次循环第一个元素为1,将第一个添加到列表后面,同理,第二次循环就是将2添加到列表的最后面
        del(AllMonkey[0])  #第一次循环删除列表的第一个元素,也就是1,然后2就变成了列表的第一个元素。同理,第二次循环就删除的2
        if i == 6:   #循环了6次之后,满足了这个条件(i == 6)
            num += 1  #循环次数加1
            print('第\033[1;31m%d\033[0m次出局猴子的编号为: \033[1;31m%d\033[0m' % (num, AllMonkey[0]))
            AllMonkey.pop(0) #循环6次之后,第7次将第7个元素出栈,删除第七个元素,继续循环下去
    if len(AllMonkey)==1: #当列表里面只剩下一个元素的时候,这时候就是我们要选出来的大王
        break #满足条件退出循环
print()
print('\033[1;31m猴子大王的编号为: %d\033[0m' % int(AllMonkey[0])) #输出猴子大王的编号

The output is as follows:
Insert picture description here
If you change the title: 15 monkeys choose kings to n monkeys choose kings, other conditions remain the same, and it's very simple, just change the code a little bit:

## 给猴子编号
## 只要是这一步需要给猴子编号,也就是创建一个列表
AllMonkey = list(range(1, int(input("请输入猴子的个数:")) + 1))

## 循环出栈
num = 0
while True:
    for i in range(1,7):
        AllMonkey.append(AllMonkey[0])
        del(AllMonkey[0])
        if i==6:
            num += 1
            print('第\033[1;31m%02d\033[0m次出局猴子的编号为: \033[1;31m%02d\033[0m' % (num, AllMonkey[0]))
            AllMonkey.pop(0)
    if len(AllMonkey)==1:
        break
print()
print('\033[1;31m猴子大王的编号为: %d\033[0m' % int(AllMonkey[0]))

The output is as follows:
Insert picture description here

Comments and discussions are welcome! ! !

Guess you like

Origin blog.csdn.net/weixin_44901564/article/details/106375908