我已經被賦予創建代碼的任務。任務如下:從python 2.7的列表中刪除每個第n個元素
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開始計數,並刪除下一個第三個元素,這是幸福等等,直到有一個人離開。
我該怎麼做?
誰能幫助我????????/ – user1839493
那麼,誰做出選擇的人總是在列表中的第一個? –
我已經使用我自己的代碼的第一部分是:下一步= 1,而len(名稱)> 1:names.pop(Next)Next = Next + step Next =(Next - 1)%len(names)打印名稱返回名稱[0],可用於返回倖存者,但是當我嘗試實現第二部分時,建議也好像它似乎不起作用 \t 我試圖使用此:assert name in survivor中的步驟名稱):如果生存者==名稱:但它不起作用它表示UnboundLocalError:在分配之前引用的局部變量'步驟'返回步驟 – user1839493