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

2024-06-01 08:03:54 发布

您现在位置: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):
    next = step

    while len(names) > 1:
        names.pop(next)
        next = next + step - 1
        if next > len(names):
            next = next - len(names)

    return names[0]

错误如下:

^{pr2}$

Tags: andofthetoinyounameswill
2条回答

因为在计算机科学中计数是从0开始的,所以您需要以与更新它相同的方式对next进行初始设置,即

next = step - 1

在给定的示例中,您正在使用N=2运行,并且应该返回Brenda,但是如果不将步骤递减1,那么您将首先弹出'Craig'。进行此更改将使代码运行并在给定的示例中输出正确的结果。在

我建议的另一个更改是使用模运算符来确保next始终是names的有效索引。它更简洁,更容易理解:

^{pr2}$

把这些放在一起,你可以得到以下结果:

def survivor(names, step):
    next = step-1

    while len(names) > 1:
        print "-", names.pop(next), "walked"
    next = (next + step - 1) % len(names)

    return names[0]

print survivor(["Andrew", "Brenda", "Craig", "Deidre", "Edward", "Felicity", "Greg", "Harriet"], 2), "survived!"

输出:

- Brenda walked
- Deidre walked
- Felicity walked
- Harriet walked
- Craig walked
- Greg walked
- Edward walked
Andrew survived!

最后,正如其他地方所指出的,不要用next这样的内置函数来命名变量。在

索引错误表示代码试图访问列表中不存在的索引。当我在每次while循环迭代结束时打印出next变量时,我得到以下信息:

5
1
3
1
3

由于python开始在0处建立索引,并且由于此时列表中只有3个元素,因此它会查找names[3],但列表只会上升到names[2]

另外,我不会使用next作为变量,因为它是一个关键字。在

相关问题 更多 >