The following code should do everything you requested, including the implementation of the safeN function:
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
Edit: Here is an example of using the code above when working with IDLE on Windows.
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') >>>