[Tutor] IndexError: list index out of range

Asokan Pichai pasokan at talentsprint.com
Tue Nov 22 04:22:05 CET 2011


On Tue, Nov 22, 2011 at 4:32 AM, Steven D'Aprano <steve at pearwood.info>wrote:

> John wrote:
>
>>
>> Hi all,
>>
>> I have wriiten the following code:
>> [Segment]
>>
>>   def survivor(names, step):
>>>>>
>>>>    index = step - 1
>>    next = names
>>    while len(next)>  1:
>>        next.remove (next[index])
>>
>
>
> What is the intention of this function? The name given doesn't mean
> anything to me. The parameters "names" and "step" don't seem meaningful.
>
I guess he is trying the Josephus problem. I am guessing from the name!

If so,  you have to remember that when you delete an item you change the
positions of subsequent items.
For example, in a 11-element list, say A,  if you want to delete every
third, the index numbers you *should* delete are 2, 5, 8. But if you delete
A[2], then you will delete the original A[6] and then the original A[10].

So you have to think in terms of 'marking' for deletion and later deleting
or deleting from the other end.

A more interesting possibility is to replicate the original list and append
it to itself and "delete" all occurrences.

About 25 years back thats what I did in BASIC and won an honorable mention
in a coding contest in a magazine :-)
I replaced the cell contents with a space and in subsequent rounds counted
non-space items.

The first prize was won by a circular(linked-)list in Pascal, with the same
repace by Space idea

HTH

Asokan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111122/0059867b/attachment.html>


More information about the Tutor mailing list