[Tutor] problem with circular list

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 23 Jul 2001 13:01:42 -0700 (PDT)


On Mon, 23 Jul 2001, Tim Condit wrote:

> > Side note: you can avoid depending on IndexError altogether by using the
> > "modulo" operator '%'.  The modulo operator is traditionally used for
> > things that "wrap around":
> > 
> > ###
> > >>> for i in range(10):
> > ...     print i % 3
> > ...
> > 0
> > 1
> > 2
> > 
> 
> I used this originally, then dropped it in favor of subtraction.. seemed
> like a good idea at the time. 

The problem with subtraction is that you have to make sure you do it
enough.  For example, let's say that we have 2 lone survivors left, and
the executioner starts humming "Fee fi fo fum, I smell the blood of an
Englishman."  That's 8 syllablus.

If our position is originally 0, then what we want is:

    (0 + 8) % 2 == 0

And the first person's gone.  However, if we're not careful with the
subtraction, what we get is something different:

    (0 + 8) - 2 == 6

and since there are only two people, that's a bug that will, justifiably,
cause an IndexError.

One solution to this is to use repeated subtraction in some sort of while
loop, which I think someone suggested in a previous message.

Hope this helps!