I can define a function that transforms either a scalar or each element in
a list as follows:
def twice(x):
try:
return map(twice,x)
except:
return 2*x
print twice(3) # 6
print twice([1,4,9]) # [2,8,18]
Is this good style? I intend to define many functions like this and want
to use the right method. Thanks.
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- 9 3248 be*******@aol.c om wrote: I can define a function that transforms either a scalar or each element in a list as follows:
def twice(x): try: return map(twice,x) except:
A bare except without the type of exception is always bad.
return 2*x
print twice(3) # 6 print twice([1,4,9]) # [2,8,18]
Is this good style? I intend to define many functions like this and want to use the right method. Thanks.
I'd say you've just discovered a use case for a decorator:
def scalarOrVector( f):
def g(arg):
try:
return map(f, arg) # or map(g, arg) if you want to allow
# nested sequences
except TypeError:
return f(arg)
return g
#@scalarOrVecto r
def twice(a):
return 2*a
twice = scalarOrVector( twice)
print twice(3) # 6
print twice([1,4,9]) # [2,8,18]
Of course you will have to ensure that map(f, arg) _does_ throw an
exception.
Peter
beliavsky <at> aol.com <beliavsky <at> 127.0.0.1> writes: def twice(x): try: return map(twice,x) except: return 2*x
[snip] Is this good style?
First a general comment about catching exceptions -- you should probably write
your try-except block as:
try:
...
except TypeError:
...
Better to only catch the exceptions that your call to map will throw.
But to really answer your question, I would probably avoid this style. It
means for every number you double (whether an element of a list, or an element
alone), you'll throw and catch an exception. This needlessly complicates the
simple case. Exception handling is intended to deal with "exceptiona l" cases,
cases which should be relatively infrequent. And while Python's exception
handling is pretty efficient, it's still not particularly cheap to catch
exceptions. You would probably be better with:
def twice(x):
if isinstance(x, list):
return map(twice, x)
else:
return 2*x
In this case, instead of incurring the cost of a thrown and caught exception
for each number, you incur only the cost of a isinstance test. You also avoid
treating the common case as the exceptional one.
Steve
P.S. In reality, I probably wouldn't write a method like this, instead
relying on the caller to call map for themselves if necessary. The caller is
much more likely to know the type of the object they want to double anyway, so
they may not even need to use the isinstance test.
You may want to take a look at isinstance() function.
def twice(x):
if isinstance(x, list): return map(twice, x)
if isinstance(x, (int, float, str)): return 2*x
return None
print twice(3) # 6
print twice([1,4,9]) # [2,8,18]
print twice('*')
HTH,
Larry Bates
Syscon, Inc.
"be*******@aol. com" <be*******@127. 0.0.1:7501> wrote in message
news:41******** **@127.0.0.1... I can define a function that transforms either a scalar or each element in a list as follows:
def twice(x): try: return map(twice,x) except: return 2*x
print twice(3) # 6 print twice([1,4,9]) # [2,8,18]
Is this good style? I intend to define many functions like this and want to use the right method. Thanks. ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet
News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000
Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption
=---
Larry Bates wrote: You may want to take a look at isinstance() function.
def twice(x): if isinstance(x, list): return map(twice, x) if isinstance(x, (int, float, str)): return 2*x return None
Actually, I'd favor the try/except approach. It's entirely reasonable
to think that, if this function might be passed either scalars or lists,
it may also be passed a non-list-based sequence object. If you simply
try using map(), then it'll work correctly for any object that follows
the expected protocol, regardless of whether that object is (a subclass
of) list. By explicitly demanding a list, you're needlessly limiting
the usefulness of the function.
Jeff Shannon
Technician/Programmer
Credit International
Jeff Shannon <jeff <at> ccvcorp.com> writes: Actually, I'd favor the try/except approach. It's entirely reasonable to think that, if this function might be passed either scalars or lists, it may also be passed a non-list-based sequence object. If you simply try using map(), then it'll work correctly for any object that follows the expected protocol, regardless of whether that object is (a subclass of) list. By explicitly demanding a list, you're needlessly limiting the usefulness of the function.
Well, you can always test for the protocol, e.g.:
def twice(x):
if hasattr(x, "__iter__") :
return map(twice, x)
else:
return 2*x
It just seems like a misuse of the construct to me to treat the most frequent
case as an exceptional one. Note that the following solution (that doesn't
recurse) wouldn't be unreasonable if you expected to pass mostly sequences to
the function:
def twice(x):
try:
return map(lambda x: 2*x, x)
except TypeError:
return 2*x
The difference here is that we are now treating the sequence case as the
simple case -- if we're dealing with a sequence, no exception handling is
required. So if the sequence case is substantially more frequent, this would
be a perfectly reasonable solution. (Note that the difference between this
and the original solution is that this version does not recurse, so, unlike
the original solution, this one will not throw an exception for every element
in the sequence.)
Steve
"Steven Bethard" <st************ @gmail.com> wrote in message
news:lo******** **************@ post.gmane.org. .. Well, you can always test for the protocol, e.g.:
def twice(x): if hasattr(x, "__iter__") : return map(twice, x)
In 2.2.1: hasattr([1,2,3], '__iter__')
0
so this does not seem to work as you seem to expect. hasattr(iter(x) ,
'__iter__') will.
Terry J. Reedy
Terry Reedy <tjreedy <at> udel.edu> writes: In 2.2.1: hasattr([1,2,3], '__iter__') 0 so this does not seem to work as you seem to expect. hasattr(iter(x) , '__iter__') will.
Yeah, I thought there was probably some special case I was missing there. The
problem with hasattr(iter(x) , '__iter__') is that iter(x) can throw an
exception if the object is not iterable: iter(1)
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: iteration over non-sequence
So if you call iter(x) in the test, and x is a number, you end up having to
try and catch the exception just like in the original solution.
Do you know at what version hasattr(x, '__iter__') started working? In 2.4a2: hasattr([1,2,3], '__iter__')
True
Steve
Terry Reedy wrote: "Steven Bethard" <st************ @gmail.com> wrote in message news:lo******** **************@ post.gmane.org. .. Well, you can always test for the protocol, e.g.:
def twice(x): if hasattr(x, "__iter__") : return map(twice, x)
In 2.2.1: hasattr([1,2,3], '__iter__') 0 so this does not seem to work as you seem to expect. hasattr(iter(x) , '__iter__') will.
No it won't:
[Python 2.2] hasattr(iter(1) , "__iter__")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: iteration over non-sequence
Here the only reliable test for iterability is to just try it.
Unfortunately, while in most cases you want to treat them as scalars,
strings are iterables, too.
In 2.3 Steven's proposal works:
hasattr(1, "__iter__")
False hasattr([], "__iter__")
True
Peter be*******@aol.c om wrote: I can define a function that transforms either a scalar or each element in a list as follows:
def twice(x): try: return map(twice,x) except: return 2*x
print twice(3) # 6 print twice([1,4,9]) # [2,8,18]
Is this good style? I intend to define many functions like this and want to use the right method. Thanks.
In addition to those options already mentioned, here's another alternative.
def twice(*args):
retval = [2*x for x in args]
if len(retval) == 1:
return retval[0]
else:
return retval
print twice() # []
print twice(3) # 6
print twice([1,4,9]) # [1, 4, 9, 1, 4, 9]
#BUT ...
print twice(*[1,4,9]) # [2,8,18]
# Note '*' -^
print twice(1,4,9) # [2,8,18]
# No '[]' --^----^
You can even omit the if ... else, if you don't mind getting a singleton
list for the one-parameter case. (i.e. twice(3) == [6]) This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Xah Lee |
last post by:
Today we'll be writing a function called Range. The Perl documentation
is as follows.
Perl & Python & Java Solutions will be posted in 48 hours.
This is Perl-Python a-day. See
http://xahlee.org/web/perl-python/python.html
Xah
xah@xahlee.org
|
by: roger |
last post by:
I'm having difficulties invoking a user defined table function,
when passing to it a parameter that is the result of another
user defined function.
My functions are defined like so:
drop function dbo.scalar_func
go
create function dbo.scalar_func()
returns int
|
by: BekTek |
last post by:
I have class that has member function that take two argument..
I'd like to use the member function to algorithm such as remove_if..
How can I bind that?
class Foo{
void f(){
int a = 10;
remove_if(list.begin(), list.end(), HERE);
|
by: Lateralus |
last post by:
headers/vector3.h: In member function ‘Vector3
Vector3::operator*(Scalar)’:
headers/vector3.h:13: error: no matching function for call to
‘Vector3::Vector3(Vector3)’
‘Vector3::Vector3(Vector3)’
headers/vector3.h:10: note: candidates are: Vector3::Vector3(Vector3&)
I'm a little confused as to what my problem is. I get this error for
any method which calls the constructor.
|
by: Nimmi Srivastav |
last post by:
Consider two functions A and B, both of which accept a variable number
of arguments (va_start, va-arg, va_end). Is there an easy way for
arguments passed to A to be, in turn, passed to B? (For example, if A
is a wrapper function around B).
Thanks,
Nimmi
| |
by: Adam |
last post by:
Hey,
Just a quick appeal for suggestions re some code, able to pass varying
numbers of arguments...
I have a function which can accept varying numbers of arguments. It in
turn calls a function whose argument list can vary in length.
At the moment, I have something along the lines of...
|
by: Carsten |
last post by:
Hello Folks,
I encountered a problem with SQL server 2000 and UDFs.
I have a scalar UDF and a table UDF where I would like the scalar UDF
to provide the argument for the table UDF like in:
SELECT
*
FROM
|
by: James Tursa |
last post by:
MVC 8.0
Windows XP
I would like to use multidimensional arrays in a function call. This
method works:
//-------------------------------------------------------------------------
void fun(double *d, int m, int n);
extern int main(void)
|
by: kovariadam |
last post by:
Hi,
Does anybody know why i get this error:
SQL0176N The second, third or fourth argument of the TRANSLATE scalar
function is incorrect. SQLSTATE=42815
with this query:
SELECT TRANSLATE(p.meno,
'aaaaccdeeeiillnnoooorrsstuuuuyzzAAAACCDEEEIILLNNOOOORRSSTUUUUYZZ',
'áâãäæèïéìëíîåµñòóôöõàø¶¹»úüûùý¼¾ÁÂÃÄÆÈÏÉÌËÍÎÅ¥ÑÒÓÔÖÕÀئ©«ÚÜÛÙݬ®')
FROM oa.pracovnik p;
|
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...
|
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,...
| |
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...
|
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...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
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();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |