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

标签 python python-2.7

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

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/

相关文章:

python - Paramiko - 使用私钥连接 - 不是有效的 OPENSSH 私钥/公钥文件

python-2.7 - 使用sklearn进行多标签特征选择

python - 如何检查 txt 文件中的每一行是否有正确的用户名和密码

python - 服务器端命令行排队

python - Django,首先继承 models.Model 还是首先继承非模型类?

python - python 中的日期范围,其中结果值必须为字符串格式

python - __metaclass__ 向创建的类添加无效属性?

java - 我无法使用 python 脚本编译和运行 java 程序

mysql - 使用 mysql 的 django 上的syncdb错误

python - 如何在 python 中打印毕达哥拉斯金字塔?