Hi,
I'm wondering if it is useful to extend the count() method of a list
to accept a callable object? What it does should be quite intuitive:
count the number of items that the callable returns True or anything
logically equivalent (non-empty sequence, non-zero number, etc).
This would return the same result as len(filter(a_ca llable, a_list)),
but without constructing an intermediate list which is thrown away
after len() is done.
This would also be equivalent to
n = 0
for i in a_list:
if a_callable(i): n += 1
but with much shorter and easier-to-read code. It would also run
faster.
This is my first post and please bear with me if I'm not posting it in
the right way.
Regards,
Ping 26 2458
On Jun 14, 2:53 pm, Ping <ping.nsr....@g mail.comwrote:
Hi,
I'm wondering if it is useful to extend the count() method of a list
to accept a callable object? What it does should be quite intuitive:
count the number of items that the callable returns True or anything
logically equivalent (non-empty sequence, non-zero number, etc).
This would return the same result as len(filter(a_ca llable, a_list)),
map and filter are basically obsolete after the introduction of list
comprehensions; your expression is equivalent to:
len([i for i in a_list if a_callable(i)])
Which can then be converted into a generator expression (round
brackets instead of square brackets) to avoid the intermediate list:
len((i for i in a_list if a_callable(i)))
Or syntactically equivalent (avoiding lispy brackets):
len(i for i in a_list if a_callable(i))
but without constructing an intermediate list which is thrown away
after len() is done.
This would also be equivalent to
n = 0
for i in a_list:
if a_callable(i): n += 1
but with much shorter and easier-to-read code. It would also run
faster.
This is my first post and please bear with me if I'm not posting it in
the right way.
Regards,
Ping
On Jun 14, 3:37 pm, Dustan <DustanGro...@g mail.comwrote:
map and filter are basically obsolete after the introduction of list
comprehensions
It is probably worth noting that list comprehensions do not require
that you write a new function; they take any expression where
appropriate. For more information on list comprehensions, see: http://docs.python.org/tut/node7.htm...00000000000000
Generator expressions are the same, except syntactically they have
round brackets instead of square, and they return a generator instead
of a list, which allows for lazy evaluation.
On Jun 14, 3:37 pm, Dustan <DustanGro...@g mail.comwrote:
Which can then be converted into a generator expression (round
brackets instead of square brackets) to avoid the intermediate list:
len((i for i in a_list if a_callable(i)))
Sorry for the excess of posts everybody.
I just realized that the generator expression would not work. I'm not
sure how else could be implemented efficiently and without using up
memory besides by accumulating the count as your earlier example shows.
On Thu, 2007-06-14 at 21:06 +0000, Dustan wrote:
On Jun 14, 3:37 pm, Dustan <DustanGro...@g mail.comwrote:
Which can then be converted into a generator expression (round
brackets instead of square brackets) to avoid the intermediate list:
len((i for i in a_list if a_callable(i)))
Sorry for the excess of posts everybody.
I just realized that the generator expression would not work. I'm not
sure how else could be implemented efficiently and without using up
memory besides by accumulating the count as your earlier example shows.
sum(1 for i in a_list if a_callable(i))
--
Carsten Haese http://informixdb.sourceforge.net
On Thu, 2007-06-14 at 12:53 -0700, Ping wrote:
Hi,
I'm wondering if it is useful to extend the count() method of a list
to accept a callable object? What it does should be quite intuitive:
count the number of items that the callable returns True or anything
logically equivalent (non-empty sequence, non-zero number, etc).
This would return the same result as len(filter(a_ca llable, a_list)),
but without constructing an intermediate list which is thrown away
after len() is done.
This would also be equivalent to
n = 0
for i in a_list:
if a_callable(i): n += 1
but with much shorter and easier-to-read code. It would also run
faster.
As an alternative to the generator-sum approach I posted in reply to
Dustan's suggestion, you could (ab)use the fact that count() uses
equality testing and do something like this:
>>class Oddness(object) :
.... def __eq__(self, other): return other%2==1
....
>>[1,2,3,4,5].count(Oddness( ))
3
I don't know which approach is faster. Feel free to compare the two.
HTH,
--
Carsten Haese http://informixdb.sourceforge.net
>
sum(1 for i in a_list if a_callable(i))
--
Carsten Haesehttp://informixdb.sour ceforge.net
This works nicely but not very intuitive or readable to me.
First of all, the generator expression makes sense only to
trained eyes. Secondly, using sum(1 ...) to mean count()
isn't very intuitive either.
I would still prefer an expression like a_list.count(a_ callable),
which is short, clean, and easy to understand. :) However,
it does produce ambiguities if a_list is a list of callables.
Should the count() method match values or check return values
of a_callable? There are several possible designs but I'm not
sure which is better.
Ping
On Jun 15, 9:15 am, Ping <ping.nsr....@g mail.comwrote:
sum(1 for i in a_list if a_callable(i))
--
Carsten Haesehttp://informixdb.sour ceforge.net
This works nicely but not very intuitive or readable to me.
First of all, the generator expression makes sense only to
trained eyes. Secondly, using sum(1 ...) to mean count()
isn't very intuitive either.
Then wrap it in a function:
def count(a_list, a_function):
return sum(1 for i in a_list if a_function(i))
And call the function. You can also give it a different name (although
I can't think of a concise name that would express it any better).
I would still prefer an expression like a_list.count(a_ callable),
which is short, clean, and easy to understand. :) However,
it does produce ambiguities if a_list is a list of callables.
Should the count() method match values or check return values
of a_callable? There are several possible designs but I'm not
sure which is better.
Indeed, the ambiguity in that situation would be a reason *not* to
introduce such behavior, especially since it would break older
programs that don't recognize that behavior. Just stick with writing
the function, as shown above.
On Fri, 2007-06-15 at 14:15 +0000, Ping wrote:
using sum(1 ...) to mean count() isn't very intuitive
I find it very intuitive, but then again, my years of studying Math may
have skewed my intuition.
I would still prefer an expression like a_list.count(a_ callable),
which is short, clean, and easy to understand.
Did you see my alternative example on this thread? It allows you to use
list.count in almost exactly that way, except that instead of passing
the callable directly, you pass an object that defers to your callable
in its __eq__ method.
HTH,
--
Carsten Haese http://informixdb.sourceforge.net
On 6 15 , 11 17 , Dustan <DustanGro...@g mail.comwrote:
On Jun 15, 9:15 am, Ping <ping.nsr....@g mail.comwrote:
sum(1 for i in a_list if a_callable(i))
--
Carsten Haesehttp://informixdb.sour ceforge.net
This works nicely but not very intuitive or readable to me.
First of all, the generator expression makes sense only to
trained eyes. Secondly, using sum(1 ...) to mean count()
isn't very intuitive either.
Then wrap it in a function:
def count(a_list, a_function):
return sum(1 for i in a_list if a_function(i))
And call the function. You can also give it a different name (although
I can't think of a concise name that would express it any better).
Hmm... This sounds like the best idea so far. It is efficient both
in memory and time while exposes an easy-to-understand name.
I would name the function count_items though.
n = count_items(a_l ist, lambda x: x 3) # very readable :)
cheers,
Ping This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: GrelEns |
last post by:
hello,
i wonder if this possible to subclass a list or a tuple and add more
attributes ? also does someone have a link to how well define is own
iterable object ?
what i was expecting was something like :
>>> t = Test('anAttributeValue', )
>>> t.anAttribute
|
by: oraustin |
last post by:
Hi all, hope you can help,
I need some sort a list box that whereby I can shade in the rows in
different colours (red, green and amber traffic light colours to
indicate priority).
Please can you tell me what I could use to achieve this on an Access
form.
Thanks
|
by: markscala |
last post by:
Problem:
You have a list of unknown length, such as this: list =
. You want to extract all and only the X's. You know
the X's are all up front and you know that the item after the last X is
an O, or that the list ends with an X. There are never O's between
X's.
I have been using something like this:
_____________________
|
by: bartonc |
last post by:
I was chasing a bug last night. I actually saw it before I inserted the trace (print) statements. This:
>>> l=range(10)
>>> for i in l:
... l.remove(i)
... print i
...
0
2
4
6
|
by: jonathanemil |
last post by:
Hello,
I am a 1st semester Computer Science student in a Python class. Our current assignment calls for us to read a list from a file, create a 2-dimensional list from the file, and check to see whether or not 2-dim list constitutes a "magic square" (i.e. all the rows, columns and diagonals equal each other when added). We are to create several definitions, and I have had no problem reading from the file, creating the list, and getting the...
| |
by: kj |
last post by:
Hi. I'd like to port a Perl function that does something I don't
know how to do in Python. (In fact, it may even be something that
is distinctly un-Pythonic!)
The original Perl function takes a reference to an array, removes
from this array all the elements that satisfy a particular criterion,
and returns the list consisting of the removed elements. Hence
this function returns a value *and* has a major side effect, namely
the target...
|
by: python_newbie |
last post by:
I don't know this list is the right place for newbie questions. I try
to implement insertion sort in pyhton. At first code there is no
problem. But the second one ( i code it in the same pattern i think )
doesn't work. Any ideas ?
------------------------------------------------------------
def insertion_sort(aList):
for i in range(len(aList)):
for j in range(i):
|
by: daokfella |
last post by:
I have a business object that exposes a collection of other objects
via a List<of Type>. How can I intercept when an item is either added
or removed from this list. Is it possible?
private List<Permission_Permissions;
public List<Permission2Permissions
{
get
{
|
by: Phantom |
last post by:
I totally need the help of the XML experts up here, I can't figure this
one out, I've been working on it for hours today, googling my brains
out.
I need to write an xpath query string that returns one or more specific
elements on the fly, in this example, apple and/or orange. *this* works
for JUST apple:
select xpath_eval('//apple',
xtree_doc('<fruit><apple>7</apple><orange>11</orange><banana
|
by: metaperl.com |
last post by:
Pyparsing has a really nice feature that I want in PLY. I want to
specify a list of strings and have them converted to a regular
expression.
A Perl module which does an aggressively optimizing job of this is
Regexp::List -
http://search.cpan.org/~dankogai/Regexp-Optimizer-0.15/lib/Regexp/List.pm
I really dont care if the expression is optimal. So the goal is
something like:
|
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: 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,...
|
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...
|
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: 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...
| |
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: 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...
| |