我接到了一个任务,要为它创建一个代码。任务如下:
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,依此类推,直到只剩下一个人。在
我该怎么做?在
这似乎有效:
它打印出海盗受害者的名字并返回幸存者的名字:
^{pr2}$下面的代码应该完成您要求的所有操作,包括实现
safeN
函数:编辑:下面是在Windows中使用IDLE时上面代码的一些用法示例。在
^{pr2}$相关问题 更多 >
编程相关推荐