以下代码应该完成您要求的一切,包括实现该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')
>>>