我被安排了以下任务:
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}$
因为在计算机科学中计数是从0开始的,所以您需要以与更新它相同的方式对
next
进行初始设置,即在给定的示例中,您正在使用
N=2
运行,并且应该返回Brenda,但是如果不将步骤递减1,那么您将首先弹出'Craig'
。进行此更改将使代码运行并在给定的示例中输出正确的结果。在我建议的另一个更改是使用模运算符来确保
^{pr2}$next
始终是names
的有效索引。它更简洁,更容易理解:把这些放在一起,你可以得到以下结果:
输出:
最后,正如其他地方所指出的,不要用
next
这样的内置函数来命名变量。在索引错误表示代码试图访问列表中不存在的索引。当我在每次while循环迭代结束时打印出
next
变量时,我得到以下信息:由于python开始在
0
处建立索引,并且由于此时列表中只有3个元素,因此它会查找names[3]
,但列表只会上升到names[2]
另外,我不会使用
next
作为变量,因为它是一个关键字。在相关问题 更多 >
编程相关推荐