473,664 Members | 2,967 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

min() with custom compare.

Hi there,
If you have a list of elements, you can sort it with an alternative
comparator (default is __lt__())

This is done as:
l=[5,-4,1,9,-9]
l.sort()
l [-9, -4, 1, 5, 9] l.sort(lambda x,y: abs(x)-abs(y))
l

[1, -4, 5, -9, 9]

Lovely stuff, is it not?

Now my question:
What if I need only a max, or min value, and not a complete sort,
but I do want to have a custom compare func.
What could I do?

min() and max() built-ins cannot take a compare func.

Thanks,

Bram

--
------------------------------------------------------------------------------
Bram Stolk, VR Engineer.
SARA Academic Computing Services Amsterdam, PO Box 94613, 1090 GP AMSTERDAM
email: br**@nospam.sar a.nl Phone +31-20-5923059 Fax +31-20-6683167

"For the costs of subsidized agriculture in the EU, we can have all 56 million
European cows fly around the world. First Class." - J. Norberg
------------------------------------------------------------------------------
Jul 18 '05 #1
4 5143
On Wed, 7 Apr 2004 11:44:07 +0200,
Bram Stolk <br**@nospam.sa ra.nl> wrote:

[ example of sort with custom compare function snipped ]
What if I need only a max, or min value, and not a complete
sort, but I do want to have a custom compare func. What could I
do? min() and max() built-ins cannot take a compare func.


Use reduce:

def absolulte_minim um_function( x, y ):
x, y = abs( x ), abs( y )
if x < y:
return x
else:
return y

minimum = reduce( absolute_minimu m_function, l )

There's probably some (awfully horrible) lambda-embeddable
equivalent to absolute_minimu m_function, but I'm not about to try
to figure it out right now, and even if I did, I'd probably end up
not using it anyway.

HTH,
Heather

--
Heather Coppersmith
That's not right; that's not even wrong. -- Wolfgang Pauli
Jul 18 '05 #2
Heather Coppersmith schrieb:
Use reduce:

def absolulte_minim um_function( x, y ):
x, y = abs( x ), abs( y )
if x < y:
return x
else:
return y

minimum = reduce( absolute_minimu m_function, l )


That doesn't work if the "minimum" element is negative, e.g.

l = [5, -4, -1, 9, -9].
# ^^
def absolute_minimu m_function(x, y):
if abs(x) < abs(y):
return x
else:
return y
minimum = reduce(absolute _minimum_functi on, l)

--
http://www.ososo.de/
Jul 18 '05 #3
Heather Coppersmith <me@privacy.net > wrote in message news:<m2******* *****@unique.ph ony.fqdn>...
On Wed, 7 Apr 2004 11:44:07 +0200,
Bram Stolk <br**@nospam.sa ra.nl> wrote:

[ example of sort with custom compare function snipped ]
What if I need only a max, or min value, and not a complete
sort, but I do want to have a custom compare func. What could I
do?
....
def absolulte_minim um_function( x, y ):
x, y = abs( x ), abs( y )
if x < y:
return x
else:
return y

minimum = reduce( absolute_minimu m_function, l )

There's probably some (awfully horrible) lambda-embeddable
equivalent to absolute_minimu m_function, but I'm not about to try
to figure it out right now, and even if I did, I'd probably end up
not using it anyway.


minimum = reduce(lambda x, y: min(abs(x), abs(y)), l)
Jul 18 '05 #4
Use DSU, as for sorts. Turn each element i of the sequence into a tuple
(f(i), i), and find the min of that sequence. Return element 1 of that
tuple, which is the original set element.
def min_f(seq, f):
decorated = [(f(i), i) for i in seq]
return min(decorated)[1]

def max_f(seq, f):
decorated = [(f(i), i) for i in seq]
return min(decorated)[1]
l=[5,-4,1,9,-9]
min(l) -9 min_f(l, abs)

1

You can make 'decorated' be a generator and avoid the need to hold the
whole list in memory:

def decorated2(seq, f):
for i in seq:
yield f(i), i

def min_f2(seq, f):
return min(decorated(s eq, f))[1]

def max_f2(seq, f):
return max(decorated(s eq, f))[1]

If you want to break ties not by comparing the original items but by
comparing indices, you could do this:
def decorated3(seq, f):
for i, v in enumerate(seq):
yield (f(v), i, v)

def min_f3(seq, f):
return min(decorated3( seq, f))[2]

Jeff

Jul 18 '05 #5

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

Similar topics

3
1665
by: Claudio Grondi | last post by:
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()
1
4021
by: yb | last post by:
Hello, I've been trying to emulate css min-width and max-width in IE. I've looked at various methods on the web, but none seemed to truly emulate min-width / max-width, or at least not very elegantly. There are two problems I've noticed: 1) padding / margin around containing element throw off calculations in IE, even in strict mode. But there should be work arounds using an
0
1124
by: Mike Moore | last post by:
We have a min and max qty fields, but we can't seem to get these to work properly. THe min qty is one of requied fields. A user can enter a min of 1 and max could be 0. We would like to implement a rule in the validator that the min can't be greater than the max and the max can't be less than the min. What would be the best approach or validator to use to get this to work. We tried a custom validator, but we are having validator firing...
5
2326
by: kevinjouco | last post by:
Hello Have searched the group for a solution to the following problem without success: Table 1 has Ref No (No Duplicates) & Min Max Value Fields ie Ref No 1 Min 1 Max 10 Ref No 2 Min 11 Max 20 etc Table 2 is linked by Ref No (Allows Duplicates) & Recorded Value
12
5790
by: Pol Bawin | last post by:
Hi All, Did somebody already define attributes for numerical properties to define value : minima, maxima, a number of decimal, ...? This information would be useful to unify syntax Polo
8
7826
by: pmud | last post by:
Hi, I am using a compare validator in asp.net application(c# code). This Custom validator is used for comparing a value enterd by the user against the primary key in the SQL database. IF the VALUE ENTERED BY THE USER EXISTS IN THE DB , then THE ERROR MESSAGE OF THE COMPARE VALIDATOR SHOULD BE DISPLAYED. For this, I used the reference artiicle "http://msdn.microsoft.com/library/default.asp?url=/library/en-...
17
2154
by: Albert Hopkins | last post by:
This issue may have been referred to in news:<mailman.1864.1196703799.13605.python-list@python.orgbut I didn't entirely understand the explanation. Basically I have this: 6.0 nan 6.0 nan Before I did not know what to expect, but I certainly didn't expect
19
29246
by: Eugeny Myunster | last post by:
I know, only simple one: #include <stdio.h> int main() { int min=0,max=0,i,arr; for(i=0;i<12;i++) arr=rand()%31-10; for(i=0;i<12;i++)
0
1456
by: =?Utf-8?B?Sm9obkJhdGVz?= | last post by:
This is my first custom installer and essentially I needed to create one that installed windows installer 3.1 then installed .Net 2.0 Service Pack 1. I could not find a pre-packaged .Net 2.o SP 1 installer package anywhere so this is my attempt. The problem seems to be that when I first created it if .NET 2.0 was installed it would not install .NET 2.0 SP1 so I commented out the line where it checks but that leads the installer to try...
0
8437
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
8861
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8778
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8549
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8636
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...
0
4185
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...
1
2764
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
2003
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1759
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.