在Python2.7中从列表中删除第n个元素

2024-06-01 10:16:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我接到了一个任务,要为它创建一个代码。任务如下:

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个人。在

我需要它,让我们假设步骤=3,然后我需要它来删除craig,然后从craig开始计数,删除下一个第3个元素felicity,依此类推,直到只剩下一个人。在

我该怎么做?在


Tags: andofthetoinyounameswill
2条回答

这似乎有效:

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]

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

^{pr2}$

下面的代码应该完成您要求的所有操作,包括实现safeN函数:

import collections
import itertools

def walk_plank(names, N):
    "Walk everyone down the plank."
    circle = collections.deque(names)
    while circle:
        circle.rotate(-N)
        yield circle.pop()

def save_last(names, N):
    "Save the last person from walking the plank."
    for name in walk_plank(names, N):
        pass
    return name

def safeN(names, name):
    "Find the best N to save someone from walking the plank."
    assert name in names, 'Name must be in names!'
    for N in itertools.count(1):
        if save_last(names, N) == name:
            return N

编辑:下面是在Windows中使用IDLE时上面代码的一些用法示例。在

^{pr2}$

相关问题 更多 >