"Philipp H. Mohr" <[EMAIL PROTECTED]> wrote: > Hello, > I got a newbie question, I have written the following distance function: > > def distance(self,element1, element2): > dist = 0 > > for n in range(len(element1)): > dist = dist + pow((element1[n] - element2[n]),2) > print 'dist' + dist > return sqrt(dist) > > > and in order to be able to use len() and index element1[] the function > needs to know that the arguments element1 and element2 are both listst or > doesn't it ?
No it doesn't; it finds out at runtime. Also they don't have to be list; any object that defines __len__ will do. > I get the following error msg: > > Traceback (most recent call last): > File "Memory.py", line 105, in ? > start.inputVector(inP2) > File "Memory.py", line 97, in inputVector > allDimensions[0].newAttribute(vector) > File "Memory.py", line 56, in newAttribute > dist = self.distance(n.getCenter,newElement) > File "Memory.py", line 75, in distance > for n in range(len(element1)): > TypeError: len() of unsized object So obviously n.getCenter is not a list. > AND if I take len out I get: > > > > Traceback (most recent call last): > File "Memory.py", line 105, in ? > start.inputVector(inP2) > File "Memory.py", line 97, in inputVector > allDimensions[0].newAttribute(vector) > File "Memory.py", line 56, in newAttribute > dist = self.distance(n.getCenter,newElement) > File "Memory.py", line 76, in distance > dist = dist + pow((element1[n] - element2[n]),2) > TypeError: unsubscriptable object Same problem; n.getCenter and/or newElement are not lists (or other subscriptable objects for that matter). Just print them before you call distance to convince yourself. By the way, you don't use 'self' anywhere, so perhaps distance should be a function, not method. Also, the pythonic way of writing it (since 2.4) is: from math import sqrt from itertools import izip def distance(sequence1, sequence2): return sqrt(sum((x-y)**2 for x,y in izip(sequence1, sequence2))) > Thank you very much for your help. > > Phil Regards, George -- http://mail.python.org/mailman/listinfo/python-list