gpt4 book ai didi

python - 从 python 2.7 中的列表中删除每个第 n 个元素

转载 作者:太空狗 更新时间:2023-10-29 23:55:16 24 4
gpt4 key购买 nike

我接到了一项为其创建代码的任务。任务如下:

You are the captain of a sailing vessel and you and your crew have been captured by pirates. The pirate captain has all of you standing in a circle on the deck of his ship trying to decide in which order you should walk the plank. Eventually he decides on the following method:

(a) The pirate captain asks you to pick a number N.

(b) The first person to walk the plank will be the Nth person (starting from you).

(c) The captain will then continue around the circle forcing every Nth person to walk the plank.

(d) Once there is only one person left, that person will be given freedom.

For example: The crew consists of: Andrew, Brenda, Craig, Deidre, Edward, Felicity, Greg and Harriet. Andrew selects N=2. The crew will walk the plank in the order: Brenda, Deidre, Felicity, Harriet, Craig, Greg, Edward. Andrew will be given freedom.

我目前的代码是:

def survivor(names, step):
names = ["Andrew", "Brenda", "Craig", "Deidre", "Edward", "Felicity", "Greg", "Harriet"]
Next = step - 1
names.pop(Next)
print names

这将从列表中删除第 n 个人,但我不确定如何遍历列表以继续删除第 n 个人。

我需要它,所以让我们假设 step = 3,然后我需要它来删除 craig,然后从 craig 开始计数并删除下一个第三个元素,即 felicity 等等,直到剩下一个人。

我该怎么做?

最佳答案

这似乎可行:

from collections import deque
def survivor(names, step):
circle = deque(names)
while len(circle) > 1:
circle.rotate(1-step)
print circle.popleft()
return circle[0]

它打印海盗受害者的名字并返回幸存者的名字:

In [17]: crew = ["Andrew", "Brenda", "Craig", "Deidre",
....: "Edward", "Felicity", "Greg", "Harriet"]

In [18]: survivor(crew, 2)
Brenda
Deidre
Felicity
Harriet
Craig
Greg
Edward
Out[18]: 'Andrew'

In [19]: survivor(crew, 3)
Craig
Felicity
Andrew
Edward
Brenda
Harriet
Deidre
Out[19]: 'Greg'

关于python - 从 python 2.7 中的列表中删除每个第 n 个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13477969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com