[Tutor] Strange list behaviour in classes

Alan Gauld alan.gauld at btinternet.com
Wed Feb 24 10:02:26 CET 2010


"James Reynolds" <eire1130 at gmail.com> wrote

> This thread inspired me to start learning object oriented as well, but it
> seems I must be missing something fundamental.

No, this has nothing to do with objects, its just a broken algorithm.

>    median = Statistics.stats.median(*a)
>    n = (self.value[m] + self.value[m+1]) / 2
> IndexError: tuple index out of range
>
> def median(self, *value_list):
>      if len(self.value) % 2 == 1:
>           m = (len(self.value) - 1)/2
>           n = self.value[m+1]
>      else:
>           m = len(self.value) / 2
>           m = int(m)
>           n = (self.value[m] + self.value[m+1]) / 2
>      return n

Consider the case where the length of value is 2.
We will use the else part of the branch.
m will have value 1
The highest index is 1 because indexes start at zero
so value[m+1] will fail with an index error.

A similar error will happen when the list has only 1 entry
since the highest index there will be zero.

You need to rethink your rules for generating the indexes
remembering that they start at zero.


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list