[Tutor] Strange list behaviour in classes
ALAN GAULD
alan.gauld at btinternet.com
Thu Feb 25 09:25:31 CET 2010
One point:
class Statistics:
def __init__(self, *value_list):
>self.value = value_list
>self.square_list= []
>def mean(self, *value_list):
>try :
>ave = sum(self.value) / len(self.value)
>except ZeroDivisionError:
>ave = 0
>return ave
You don't use value_list here you use self.value. So you don't need value_list
def median(self, *value_list):
>if len(self.value) <= 2:
>n = self.mean(self.value)
>elif 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-1] + self.value[m]) / 2
>return n
Same here...
def variance(self, *value_list):
>average = self.mean(*self.value)
>for n in range(len(self.value)):
>square = (self.value[n] - average)**2
>self.square_list.append(square)
>try:
>var = sum(self.square_list) / len(self.square_list)
>except ZeroDivisionError:
>var = 0
>return var
And here...
def stdev(self, *value_list):
>var = self.variance(*self.value)
>sdev = var**(1/2)
>return sdev
And here...
def zscore(self, x, *value_list):
>average = self.mean(self.value)
>sdev = self.stdev(self.value)
>try:
>z = (x - average) / sdev
>except ZeroDivisionError:
>z = 0
>return z
And here....
a = [1,2,3,4,5,6,7,8,9,10]
>stats = Statistics(*a)
>So you need the *a here
mean = stats.mean(*a)
>median = stats.median(*a)
>var = stats.variance(*a)
>stdev = stats.stdev(*a)
>z = stats.zscore(5, *a)
>But you don't need to pass in *a in any of these calls.
Its already stored in the object.
Also instead of returning these values (or as well as)
you could have stored them as variables inside the
object.
print(mean, median, var, stdev, z)
>
>In which case this would become
print(self.theMean,self.theMedian, etc...)
Just an alternative for consideration.
Alan G.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100225/2675610f/attachment-0001.html>
More information about the Tutor
mailing list