[Catalog-sig] Questions about efficiency.

Martin v. Loewis martin@loewis.home.cs.tu-berlin.de
Mon, 28 May 2001 01:23:55 +0200


> I wrote two functions which receive a sequence and return a list with 
> non-duplicate elements. As per "unique" function's Tim Peters (as is in 
> Python Cookbook:

Hi Luis,

catalog-sig is probably not the right place to ask this question. What
made you send it here? (this is a serious question, because of all the
SIG lists I read, catalog-sig gets most off-topic questions)

In any case, sending your question to python-list@python.org would
have been better.

> my functions use the slowest method by brute force. I'd want to know why 
> and which of my functions is better or efficient and why.
> 
> def onlyOne1(s)
> 	r = []
> 	for x in s:
> 		if x not in r:
> 			r.append(x)
> 	return r
> 
> def onlyOne2(s):
> 	r = []
> 	for x in s:
> 		try:
> 			r.index(x)
> 		except:
> 			r.append(x)
> 	return r

The difference between these functions is minimal. Version 2 is
probably slightly slower, since it has to do exception handling in
case the object is not found in r, plus it does one more function
call.

However, the differences in timing should really be minor, compared to
the typical approach, which is to assume that all elements can be
hashed.

Regards,
Martin