473,795 Members | 3,175 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

New restrain builtin function?

Hi all,

In several occasions, I found myself looking for a function that would
take a value and restrict is within a specified set of boundaries. For
a 1-dimension value, I could simply write

min(max(value,t heMin),theMax)

to restrict value within the range made of theMin to theMax.
It assumes that theMax >= theMin.

I was looking for a single call to restrict a value within bounds that
would do pretty much that, so i wrote this trivial one:

def restrain(value, theMin, theMax) :
"""Return a value that is in restricted to the [theMin, theMax] range.

**Example**
for val in xrange(-1,7,1): ... print "restrain(%d,1, 5) = %d" % (val, restrain(val,1, 5))
...
restrain(-1,1,5) = 1
restrain(0,1,5) = 1
restrain(1,1,5) = 1
restrain(2,1,5) = 2
restrain(3,1,5) = 3
restrain(4,1,5) = 4
restrain(5,1,5) = 5
restrain(6,1,5) = 5

"""

assert(theMax >= theMin)
return min(max(value,t heMin),theMax)
Without the assertion check, the restrain() named function runs
expectedly slower than the explicit min(max()) calls:

C:\Python23\Lib >timeit "min(max(5,1),0 )"
1000000 loops, best of 3: 1.02 usec per loop

C:\Python23\Lib >timeit -s"from ut import restrain" "restrain(5,1,6 )"
1000000 loops, best of 3: 1.53 usec per loop

Again, I found myself writing code that has to restrain the values to
some range and prefer using the restrain() function instead of the
min(max()) one.

Therefore, I was wondering if it would it make sense to add a function
like restrain() to the list of Python built-ins. Or is there something
like that already in the Python library?
Thanks

Pierre

Jul 18 '05 #1
2 1619
"Pierre Rouleau" <pr******@impat hnetworks.com> wrote in message
news:xK******** ************@ne ws20.bellglobal .com...
Hi all,

In several occasions, I found myself looking for a function that would
take a value and restrict is within a specified set of boundaries. For
a 1-dimension value, I could simply write

min(max(value,t heMin),theMax)

to restrict value within the range made of theMin to theMax.
It assumes that theMax >= theMin.

I was looking for a single call to restrict a value within bounds that
would do pretty much that, so i wrote this trivial one:

def restrain(value, theMin, theMax) :
"""Return a value that is in restricted to the [theMin, theMax] range.
**Example**
>>> for val in xrange(-1,7,1): ... print "restrain(%d,1, 5) = %d" % (val, restrain(val,1, 5))
...
restrain(-1,1,5) = 1
restrain(0,1,5) = 1
restrain(1,1,5) = 1
restrain(2,1,5) = 2
restrain(3,1,5) = 3
restrain(4,1,5) = 4
restrain(5,1,5) = 5
restrain(6,1,5) = 5 >>>
"""

assert(theMax >= theMin)
return min(max(value,t heMin),theMax)
Without the assertion check, the restrain() named function runs
expectedly slower than the explicit min(max()) calls:

C:\Python23\Lib >timeit "min(max(5,1),0 )"
1000000 loops, best of 3: 1.02 usec per loop

C:\Python23\Lib >timeit -s"from ut import restrain" "restrain(5,1,6 )"
1000000 loops, best of 3: 1.53 usec per loop

Again, I found myself writing code that has to restrain the values to
some range and prefer using the restrain() function instead of the
min(max()) one.

Therefore, I was wondering if it would it make sense to add a function
like restrain() to the list of Python built-ins. Or is there something
like that already in the Python library?
Thanks

Pierre


I know I've wanted that on (infrequent) occasion. I think
"minmax" makes a better name, though, and I suspect it
would have to be implemented in C to make any sense,
performancewise .

John Roth

Jul 18 '05 #2
John Roth wrote:
"Pierre Rouleau" <pr******@impat hnetworks.com> wrote in message
news:xK******** ************@ne ws20.bellglobal .com...
Hi all,

In several occasions, I found myself looking for a function that would
take a value and restrict is within a specified set of boundaries. For
a 1-dimension value, I could simply write

min(max(value ,theMin),theMax )

to restrict value within the range made of theMin to theMax.
It assumes that theMax >= theMin.

I was looking for a single call to restrict a value within bounds that
would do pretty much that, so i wrote this trivial one:

def restrain(value, theMin, theMax) :
"""Return a value that is in restricted to the [theMin, theMax]


range.
**Example**
>>> for val in xrange(-1,7,1):

... print "restrain(%d,1, 5) = %d" % (val, restrain(val,1, 5))
...
restrain(-1,1,5) = 1
restrain(0,1,5) = 1
restrain(1,1,5) = 1
restrain(2,1,5) = 2
restrain(3,1,5) = 3
restrain(4,1,5) = 4
restrain(5,1,5) = 5
restrain(6,1,5) = 5
>>>

"""

assert(theMax >= theMin)
return min(max(value,t heMin),theMax)
Without the assertion check, the restrain() named function runs
expectedly slower than the explicit min(max()) calls:

C:\Python23\L ib>timeit "min(max(5,1),0 )"
1000000 loops, best of 3: 1.02 usec per loop

C:\Python23\L ib>timeit -s"from ut import restrain" "restrain(5,1,6 )"
1000000 loops, best of 3: 1.53 usec per loop

Again, I found myself writing code that has to restrain the values to
some range and prefer using the restrain() function instead of the
min(max()) one.

Therefore, I was wondering if it would it make sense to add a function
like restrain() to the list of Python built-ins. Or is there something
like that already in the Python library?
Thanks

Pierre

I know I've wanted that on (infrequent) occasion. I think
"minmax" makes a better name, though, and I suspect it
would have to be implemented in C to make any sense,
performancewise .

John Roth

I would prefer 'limit' than 'minmax' myself if 'restrain' was not
'retained' ;-)

Pierre Rouleau

Jul 18 '05 #3

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

Similar topics

5
1966
by: Blair Hall | last post by:
Can anyone please tell me how to correctly use a built in function when there is a function of the same name in local scope? Here is an example. Suppose the following is in myApply.py: def apply(func,seq): # # Code can default to # built-in definition in some cases: return __builtins__.apply(func,seq)
3
2909
by: Gonçalo Rodrigues | last post by:
Hi, Does anyone know if and how I can, from within Python, read the signatures of builtin methods/functions? The following fails: >>> import inspect >>> inspect.getargspec(list.append) Traceback (most recent call last):
2
5163
by: BJörn Lindqvist | last post by:
A problem I have occured recently is that I want to subclass builtin types. Especially subclassing list is very troublesome to me. But I can't find the right syntax to use. Take for example this class which is supposed to be a representation of a genome: class Genome(list): def __init__(self): list.__init__(self) self = ....
1
2156
by: Stephen Ferg | last post by:
Python has a builtin class for staticmethod. Seems to me that Python should also have a builtin class for abstractmethod. Something like this... ####################################### # simulated implementation of a new builtin class: abstractmethod def abstractmethod(f): methodName = f.__name__ def temp(self, *args, **kwargs):
11
1933
by: rmm | last post by:
If I replace the open builtin eg import main __main__.__builtins__.open=None Is there any way, from here on, to access the original open function?? Extending this slightly, lets say I put a reference to the original open function inside a class called Isolate and protect this reference using __getattribute__ and __setattr__. Is the original function now
10
1901
by: Shayne Wissler | last post by:
I've overloaded the global new operator, so that I can, detect when I've run out of memory: extern void* operator new(size_t s) { void *r = malloc(s); if (!r && s) { fprintf(stderr, "Error: No more memory."); exit(1); } return r;
6
5584
by: Anders K. Olsen | last post by:
Hello group I'm trying to list the users and groups who has read access to a file. I use .NET 2.0 and FileInfo.GetAccessControl().GetAccessRules(...) and then loop through the FileSystemAccessRule objects. Using these objects, it is easy to use rule.IdentityReference.Translate(typeof(NTAccount)) to get the NTAccount object. I have noticed that some of the NTAccounts can belong to BUILTIN domains,
0
1674
by: nejucomo | last post by:
Hi folks, Quick Synopsis: A test script demonstrates a memory leak when I use pythonic extensions of my builtin types, but if I use the builtin types themselves there is no memory leak. If you are interested in how builtin/pure-python inheritance interacts
6
2562
by: =?iso-8859-1?q?Erik_Wikstr=F6m?= | last post by:
Is there some way to get a function-pointer to the operators of the builtin types? In the following example I have a generic function which applies an operator on two values, however it does not work on builtin types, is there a way to make this work? struct Test { int i; Test(int i_) : i(i_) { } Test operator+(Test& t) { return Test(i + t.i); }
0
9672
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
9519
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
10213
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
7538
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
6780
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5436
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
4113
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
3722
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2920
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.