passing arguments to a function - do I need type ?

Jorgen Grahn jgrahn-nntq at algonet.se
Sun Jul 10 14:35:08 CEST 2005


(You posted your question as a followup to oen of Xah Lee's musings.
That is not the best of ideas, since people with threaded newsreaders
tend not to see it. Just post (creating a new thread) next time.)

On Sun, 10 Jul 2005 11:19:31 +0100 (BST), Philipp H. Mohr <phm4 at kent.ac.uk> 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 ?

Yeah, or something else supporting len(x) and x[n].

> I get the following error msg:
...
> TypeError: len() of unsized object
...
> AND if I take len out I get:
...
> TypeError: unsubscriptable object

Well, that depends on the types of the arguments
you're passing to the method, doesn't it? A call like

  distance([1,1], [0,0])

works fine for me. And here is a slightly simpler implementation
which avoids len (thus accepting a wider range of argument types)
and pow:

def distance(element1, element2):
    dist=0
    for a, b in zip(element1, element2):
        n = float(a-b)
        dist += n*n
    return math.sqrt(dist)

(Dunno if that's the correct formula for n-dimensional distance.
I have forgotten way too much math in the past ten years.)

/Jorgen

-- 
  // Jorgen Grahn <jgrahn@       Ph'nglui mglw'nafh Cthulhu
\X/                algonet.se>   R'lyeh wgah'nagl fhtagn!



More information about the Python-list mailing list