473,382 Members | 1,689 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

Why does min(A,B) behave different for lists and for classes?

Trying to understand the outcome of the recent
thread (called later reference thread):

"Speed quirk: redundant line gives six-fold speedup"

I have put following piece of Python code together:

class PythonObject_class:
pass
PythonObject_class_instanceA = PythonObject_class()
PythonObject_class_instanceB = PythonObject_class()
PythonObject_list_instanceA = [1]
PythonObject_list_instanceB = [1]

print "min(A,B) is A: "
print "in case of classes as parameter: " +
str(min(PythonObject_class_instanceA, PythonObject_class_instanceB) is
PythonObject_class_instanceA)
print "in case of lists as parameter: " +
str(min(PythonObject_list_instanceA, PythonObject_list_instanceB) is
PythonObject_list_instanceA)
print "min(B,A) is A: "
print "in case of classes as parameter: " +
str(min(PythonObject_class_instanceB,
PythonObject_class_instanceA) is PythonObject_class_instanceA)
print "in case of lists as parameter: " +
str(min(PythonObject_list_instanceB,
PythonObject_list_instanceA) is PythonObject_list_instanceA)

getting as output:

min(A,B) is A:
in case of classes as parameter: True
in case of lists as parameter: True
min(B,A) is A:
in case of classes as parameter: True
in case of lists as parameter: False

Is there any deeper reason I don't understand
explaining why does min(A,B) behave different
for classes than for lists?
It makes for me currently not much sense how it
behaves for classes, because the result is according
to the postings in the above mentioned reference
thread nondeterministic.

Claudio
Aug 26 '05 #1
3 1646
Claudio Grondi wrote:
Is there any deeper reason I don't understand
explaining why does min(A,B) behave different
for classes than for lists?


Yes, the sort order for lists is determined by their contents. With
your example, the lists have identical contents, so min() returns the
first minimum value encountered which is A for min(A,B) and B for
min(B,A).

For instances, the sort order is determined by custom __cmp__ or rich
comparision methods. In the absence of those, the default ordering is
determined by the object's id. In your example, the default is used
and either object may be returned as the minimum depending on which
object id is a higher number (that is an implementation and state
dependent). Since the two objects have unique ids, min() will
consistently find one to be lower than the other irrespective of
argument order, if min(A,B) is A, then min(B,A) will also be A.

The best way to develop your understanding here is view the object ids
for the instances and experiment with the results of A<B, A<=B, A==B,
etc.

Then write a simple, pure python version of min() that returns the
first occurence of the lowest valued element. Trace through its
execution and all will become clear.
Raymond

Aug 26 '05 #2
Thanks to Raymond for his reply.

If I understand him right, there is no problem with
min() as such, but with the definition of the class, which
when used in min() should define at least __cmp__().

I have attached code with another
class PythonObject_classWithDefined__cmp__:
where the behaviour of min() is like I would
expect it.

Using classes without defined __cmp__ in comparison
operations violates the directive:
"Explicit is better than implicit"
and is just to be considered bad programming
style or to name it more directly, just a way of
obfuscating code, right?

The still open question for me then is:
Why does min() not raise an error in case
there is no comparison function definition
for the feeded objects available?

Claudio

ATTACHMENT:

class PythonObject_classWithDefined__cmp__:
def __init__(self, value = 1):
self.value = value
#:def
def __cmp__(self, otherInstance):
if ( self.value < otherInstance.value ):
return -1
elif(self.value == otherInstance.value ):
return 0
else:
return 1
#:if/else
#:def
#:class

PythonObject_classWithDefined__cmp__instanceA =
PythonObject_classWithDefined__cmp__()
PythonObject_classWithDefined__cmp__instanceB =
PythonObject_classWithDefined__cmp__()
print "min(A,B) is A: "
print "in case of classes with defined __cmp__() as parameter: " +
str(min(PythonObject_classWithDefined__cmp__instan ceA,
PythonObject_classWithDefined__cmp__instanceB) is
PythonObject_classWithDefined__cmp__instanceA)
print "min(B,A) is A: "
print "in case of classes with defined __cmp__() as parameter: " +
str(min(PythonObject_classWithDefined__cmp__instan ceB,
PythonObject_classWithDefined__cmp__instanceA) is
PythonObject_classWithDefined__cmp__instanceA)

outputs:

min(A,B) is A:
in case of classes with defined __cmp__() as parameter: True
min(B,A) is A:
in case of classes with defined __cmp__() as parameter: False
"Raymond Hettinger" <py****@rcn.com> schrieb im Newsbeitrag
news:11**********************@o13g2000cwo.googlegr oups.com...
Claudio Grondi wrote:
Is there any deeper reason I don't understand
explaining why does min(A,B) behave different
for classes than for lists?


Yes, the sort order for lists is determined by their contents. With
your example, the lists have identical contents, so min() returns the
first minimum value encountered which is A for min(A,B) and B for
min(B,A).

For instances, the sort order is determined by custom __cmp__ or rich
comparision methods. In the absence of those, the default ordering is
determined by the object's id. In your example, the default is used
and either object may be returned as the minimum depending on which
object id is a higher number (that is an implementation and state
dependent). Since the two objects have unique ids, min() will
consistently find one to be lower than the other irrespective of
argument order, if min(A,B) is A, then min(B,A) will also be A.

The best way to develop your understanding here is view the object ids
for the instances and experiment with the results of A<B, A<=B, A==B,
etc.

Then write a simple, pure python version of min() that returns the
first occurence of the lowest valued element. Trace through its
execution and all will become clear.
Raymond


Aug 26 '05 #3
[Claudio Grondi]
The still open question for me then is:
Why does min() not raise an error in case
there is no comparison function definition
for the feeded objects available?


Actually, there is a comparison function for
class instances. Unfortunately, the default
method is not very useful in your case. It
works a bit like this:

def __cmp__(self, other):
return cmp(id(self), id(other))

This is mildly useful as it allows distinct
objects to have an ordering relation.
Raymond

Aug 26 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: javaguy | last post by:
I have a table I hide show/hide through a pair of divs. The show/hide part works fine in both Mozilla and MSIE. When switching between the hide and show versions the Mozilla browser keeps them in...
5
by: Dung Ping | last post by:
The following code produces different dates on different browers on my computer. For today on the IE it is: 2005.9.27 which is correct, but on FF is: 105.9.27 which in incorrect. I copied the...
5
Min
by: Gregc. | last post by:
Hi I am trying to find the min of a list of numbers. For example, if a user enters 10 numbers 1,2,3,4,5,6,7,8,9,9 then the min would be 1. I've looked as past posts on the topic, and there was...
1
by: Richard | last post by:
A menu page has a set of A tages in a UL The menu (in IE) will only get the hover visualization if the mouse rolls over underlined text. I want it to happen if the rollover occurs anywhere in...
11
by: JJLaRocque | last post by:
Hi all, Is there a simple python function to return the list index of the minimum entry in a list of lists? ie, for , , ] to return 2,4. Or, same question but just for a list of numbers, not a...
11
by: rshepard | last post by:
I start with a list of tuples retrieved from a database table. These tuples are extracted and put into individual lists. So I have lists that look like this: . When I concatenate lists, I end up...
4
by: dsdevonsomer | last post by:
Hello, I have one simple query joining two tables with left outer join on 3 fields and using MIN on two fields. These two tables have lot of data about 3 mil in total. I am trying to migrate db...
4
by: Ian Hobson | last post by:
Hi all, http://htmlgems.com/example/ex2b.html is the example page. Can someone please tell me why it causes IE to lock up using 100% of the CPU, when viewed in a screen less than 700px wide? ...
0
by: labmonkey111 | last post by:
I'm trying to get a list of page links for a report, and I'm running into a problem with IE. I have a group of nested left-floating DIVs for the page menu, inside a table. Firefox expands the size of...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.