473,805 Members | 1,887 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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_cl ass:
pass
PythonObject_cl ass_instanceA = PythonObject_cl ass()
PythonObject_cl ass_instanceB = PythonObject_cl ass()
PythonObject_li st_instanceA = [1]
PythonObject_li st_instanceB = [1]

print "min(A,B) is A: "
print "in case of classes as parameter: " +
str(min(PythonO bject_class_ins tanceA, PythonObject_cl ass_instanceB) is
PythonObject_cl ass_instanceA)
print "in case of lists as parameter: " +
str(min(PythonO bject_list_inst anceA, PythonObject_li st_instanceB) is
PythonObject_li st_instanceA)
print "min(B,A) is A: "
print "in case of classes as parameter: " +
str(min(PythonO bject_class_ins tanceB,
PythonObject_cl ass_instanceA) is PythonObject_cl ass_instanceA)
print "in case of lists as parameter: " +
str(min(PythonO bject_list_inst anceB,
PythonObject_li st_instanceA) is PythonObject_li st_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 nondeterministi c.

Claudio
Aug 26 '05 #1
3 1670
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_cl assWithDefined_ _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_cl assWithDefined_ _cmp__:
def __init__(self, value = 1):
self.value = value
#:def
def __cmp__(self, otherInstance):
if ( self.value < otherInstance.v alue ):
return -1
elif(self.value == otherInstance.v alue ):
return 0
else:
return 1
#:if/else
#:def
#:class

PythonObject_cl assWithDefined_ _cmp__instanceA =
PythonObject_cl assWithDefined_ _cmp__()
PythonObject_cl assWithDefined_ _cmp__instanceB =
PythonObject_cl assWithDefined_ _cmp__()
print "min(A,B) is A: "
print "in case of classes with defined __cmp__() as parameter: " +
str(min(PythonO bject_classWith Defined__cmp__i nstanceA,
PythonObject_cl assWithDefined_ _cmp__instanceB ) is
PythonObject_cl assWithDefined_ _cmp__instanceA )
print "min(B,A) is A: "
print "in case of classes with defined __cmp__() as parameter: " +
str(min(PythonO bject_classWith Defined__cmp__i nstanceB,
PythonObject_cl assWithDefined_ _cmp__instanceA ) is
PythonObject_cl assWithDefined_ _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.goo glegroups.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
3072
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 small width, about 740 pixels. When switching between show/hide with MSIE the "show" table wants to display about 960 pixels. If I set the outer table to ' style="table-layout: fixed;" ' then MSIE chooses to force the width to 960 pixels.
5
1507
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 code free from somewhere. Are the different displays the fault of browser, computer or code? Thanks. <script type="text/javascript" language="javascript">
5
1802
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 one that mentioned macro's. Could someone explain how do macro's (if at all) work within the C programming environment. Thanks
1
8395
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 the A cell (which appears to have been expanded to fill the LI container it is in). In FF 1.0.5.2 and Opera 9 things work as expected. How might the CSS be changed to ensure (in IE) the mouse rolling over
11
8787
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 list of lists. Thanks, Josh
11
1780
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 with a list of lists that looks like this: . ]. Then, I average the column values so I end up with a single list, but with two brackets on each end, for example, ]. Unfortunately, when I try to use that last list in a NumPy function, I'm told...
4
2623
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 from MS Access to SQL 2005. I get about 689000 rows in SQL Server, vs 863000 rows in MS Access. SELECT T1., T1., T2., MIN ( T1.), MIN(T1. ), T1.COUNT
4
1363
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? And also what, if anything I can do about it. I have tried no div, a div within body with ID - nothing I have tried
0
1814
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 the table to see the entire menu, but IE does not, the last few are cut off. After a couple of hours of testing, I have determined that IE is not using the min-width when calculating the width of the DIV, but does use the min-width when displaying...
0
9716
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9596
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10105
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7646
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5542
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5677
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4323
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3845
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3007
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.