题目:编写程序,模拟报数游戏。有n个人围成一圈,顺序编号,从第一个人开始从1到k(假设k=3)报数,报到k的人退出圈子,然后圈子缩小,从下一个人继续游戏,问最后留下的是原来的第几号。

思路:

初步实现功能,使用集合输出剩下的数字,而未考虑是第几号(每次从头开始报数)

n = 10
k = 3
people = [i for i in range(0, n+1)]

remain = {}
removePeople = []
while n>= k:
    cancel = people.pop(k-1)
    # 所有退出的人
    removePeople.append(cancel)
    print(removePeople)
    # 剩下的人
    remain = set(people) - set(removePeople)
    n = n -1
print(remain)
#输出
[2]
[2, 3]
[2, 3, 4]
[2, 3, 4, 5]
[2, 3, 4, 5, 6]
[2, 3, 4, 5, 6, 7]
[2, 3, 4, 5, 6, 7, 8]
[2, 3, 4, 5, 6, 7, 8, 9]
{0, 1, 10}

完成剩下数字对应的号,使用列表(每次从头开始报数)

"""完成剩下数字对应的号"""
n = 10
k = 3
people = [i for i in range(1, n+1)]

remain = []
removePeople = []
while n>= k:
    cancel = people.pop(k-1)
    # 所有退出的人
    removePeople.append(cancel)
    # print(removePeople)
    # 剩下的人
    remain = [num for num in people if num not in removePeople]
    n = n -1
    #剩下人对应的原始序号
    index = [people.index(j) for j in remain]
print(remain)
print(index)
#输出
print(remain)
[1, 2]
print(index)
[0, 1]

每次从下一个人开始报数

"""从下一个人开始报数"""
n = 10
k = 3
people = [i for i in range(0, n+1)]

removePeople = []
index = k-1
while len(people)>= k:
    index = (index + len(people))%len(people)
    cancel = people.pop(index)
    # 所有退出的人
    removePeople.append(cancel)
    index = index + k - 1

print(people)
print(removePeople)
#输出
[1, 6]
[2, 5, 8, 0, 4, 9, 3, 10, 7]
#输出剩下的数字及其在原始列表中的序号
"""从下一个人开始报数"""
n = 10
k = 3
people = [i for i in range(1, n+1)]

removePeople = []
index = k-1
newPeople = people[:]
removePeople = []
while len(newPeople)>= k:
    index = (index + len(newPeople))%len(newPeople)
    # print(index)
    cancel = newPeople.pop(index)
    # 所有退出的人
    removePeople.append(cancel)
    index = index + k - 1

newIndex=[people.index(i) for i in newPeople]
print(newPeople, newIndex, sep='\n')

输出:

[4, 10]

[3, 9]

#遍历补充知识:列表中的序号及数值方法https://blog.csdn.net/jarwis/article/details/119323272

list = ['html', 'js', 'css', 'python']

# 方法1
for i in list:
print ("序号:%s 值:%s" % (list.index(i) + 1, i))

# 方法2
for i in range(len(list)):
print ("序号:%s 值:%s" % (i + 1, list[i]))

# 方法3
for i, val in enumerate(list):
print ("序号:%s 值:%s" % (i + 1, val))
# enumerate()函数的第二个参数只是改变了序号的起始值
for i, val in enumerate(list, 2):
print ("序号:%s 值:%s" % (i + 1, val))
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐