6

コードを作成するタスクが与えられました。タスクは次のとおりです。

あなたは帆船の船長で、あなたと乗組員は海賊に捕らえられました。海賊の船長は、船の甲板で輪になって立ち、板を歩く順番を決めようとしています。最終的に、彼は次の方法を決定します。

(a) 海賊の船長はあなたに数字の N を選ぶように言いました.

(b) 板を最初に歩く人は、(あなたから始めて) N 番目の人になります。

(c) 船長はその後、N 人ごとに厚板を歩くように強制して円の周りを回り続けます。

(d) 一人になったら、その人には自由が与えられます。

例: 乗組員は、アンドリュー、ブレンダ、クレイグ、デイドル、エドワード、フェリシティ、グレッグ、ハリエットで構成されています。Andrew は N=2 を選択します。乗組員は、ブレンダ、デイドル、フェリシティ、ハリエット、クレイグ、グレッグ、エドワードの順に板を歩きます。アンドリューには自由が与えられます。

私がこれまでに持っているコードは次のとおりです。

def survivor(names, step):
    names =  ["Andrew", "Brenda", "Craig", "Deidre", "Edward", "Felicity", "Greg", "Harriet"]
    Next = step - 1
    names.pop(Next)
    print names

これにより、リストから最初の n 人目が削除されますが、リストをループして n 人目を削除し続ける方法がわかりません。

私はそれが必要なので、ステップ= 3と仮定して、クレイグを削除し、クレイグから数えて次の3番目の要素であるフェリシティを削除する必要があります.1人が残るまで.

これどうやってするの?

4

2 に答える 2

1

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 を使用している場合の上記のコードの使用例を次に示します。

Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:55:48) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import collections, 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

>>> names = 'Andrew Brenda Craig Deidre Edward Felicity Greg Harriet'.split()
>>> tuple(walk_plank(names, 2))
('Brenda', 'Deidre', 'Felicity', 'Harriet', 'Craig', 'Greg', 'Edward', 'Andrew')
>>> save_last(names, 2)
'Andrew'
>>> safeN(names, 'Andrew')
2
>>> safeN(names, 'Brenda')
19
>>> save_last(names, 19)
'Brenda'
>>> tuple(walk_plank(names, 19))
('Craig', 'Harriet', 'Andrew', 'Felicity', 'Deidre', 'Edward', 'Greg', 'Brenda')
>>> 
于 2012-11-20T21:22:06.897 に答える