[Tutor] Python code trouble!

John nidianjs at hotmail.com
Tue Nov 22 11:50:39 CET 2011


Hi all,

I have attempted to create a programme which removes every Nth person 
from the list until there is only one name remaining. N is inputted by 
the user.

Here is the code:

def survivor(names, step):
     next = names
     while len(next) > 1:
      index = step - 1
      next.remove (next[index])
         index = index + step - 1
         while index > len(next):
             index = index - len(next)
         if index == len(next):
             index = 0
     return names[0]



To me is appears to be correct, however when i test it i get the 
following message:



 >>> survivor(["Andrew", "Brenda", "Craig", "Deidre", "Edward", 
"Felicity", "Greg", "Harriet"], 4)
['Andrew', 'Brenda', 'Craig', 'Deidre', 'Edward', 'Felicity', 'Greg', 
'Harriet'] 3
['Andrew', 'Brenda', 'Craig', 'Edward', 'Felicity', 'Greg', 'Harriet'] 3
['Andrew', 'Brenda', 'Craig', 'Felicity', 'Greg', 'Harriet'] 3
['Andrew', 'Brenda', 'Craig', 'Greg', 'Harriet'] 3
['Andrew', 'Brenda', 'Craig', 'Harriet'] 3
['Andrew', 'Brenda', 'Craig'] 3

Traceback (most recent call last):
   File "<pyshell#68>", line 1, in <module>
     survivor(["Andrew", "Brenda", "Craig", "Deidre", "Edward", 
"Felicity", "Greg", "Harriet"], 4)
   File "<pyshell#67>", line 6, in survivor
     next.remove (next[index])
IndexError: list index out of range


Any ideas?


More information about the Tutor mailing list