473,386 Members | 1,602 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

itertools.ilen?

Sometimes I find myself simply wanting the length of an iterator. For
example, to collect some (somewhat useless ;)) statistics about a program
of mine, I've got code like this:

objs = gc.get_objects()
classes = len([obj for obj in objs if inspect.isclass(obj)])
functions = len([obj for obj in objs if inspect.isroutine(obj)])
modules = len([obj for obj in objs if inspect.ismodule(obj)])
dicts = len([obj for obj in objs if type(obj) == types.DictType])
lists = len([obj for obj in objs if type(obj) == types.ListType])
tuples = len([obj for obj in objs if type(obj) == types.TupleType])

Now, obviously I can (and will, now that 2.3 is officially released :))
replace the list comprehensions with itertools.ifilter, but I need an
itertools.ilen to find the length of such iterators.

I can imagine such a need arises in more useful situations than this, but
this is the particular case that brought the need to mind.

The Python code is simple, obviously:

def ilen(iterator):
i = 0
for _ in iterator:
i += 1
return i

But it's a pity to use itertools' super-fast iterators and have to use slow,
raw Python to determine their length :)

Jeremy
Jul 18 '05 #1
10 3341

"Jeremy Fincher" <fi*******@osu.edu> wrote in message
news:bg**********@news.cis.ohio-state.edu...
Sometimes I find myself simply wanting the length of an iterator.
An iterator is a function/method that traverses (or possibly
generates) a seqeuence. The sequence has a length (actual or
potential) but the iterator does not.
For example, to collect some (somewhat useless ;))
statistics about a program of mine, I've got code like this:

objs = gc.get_objects()
classes = len([obj for obj in objs if inspect.isclass(obj)])
functions = len([obj for obj in objs if inspect.isroutine(obj)]) modules = len([obj for obj in objs if inspect.ismodule(obj)]) dicts = len([obj for obj in objs if type(obj) == types.DictType]) lists = len([obj for obj in objs if type(obj) == types.ListType]) tuples = len([obj for obj in objs if type(obj) == types.TupleType])

Alternative: initialize six counters to 0. Scan list once and update
appropriate counter.
Now, obviously I can (and will, now that 2.3 is officially released :)) replace the list comprehensions with itertools.ifilter, but I need an itertools.ilen to find the length of such iterators.
You mean the associated sequence.
I can imagine such a need arises in more useful situations than this, but this is the particular case that brought the need to mind.

The Python code is simple, obviously:

def ilen(iterator):
i = 0
for _ in iterator:
i += 1
return i

But it's a pity to use itertools' super-fast iterators and have to use slow, raw Python to determine their length :)


If you mean a c-coded counter (which would not be an iterator itself)
equivalent to the above, that could be done. Perhaps len() could be
upgraded/extended to accept an iterator and count when it can't get a
__len__ method to call. The main downside is that iterators are
sometimes destructive (run once only).

In the meanwhile, is this really a bottleneck for you? or merely the
'pity' of a program running in 1 sec when 0.1 is possible?

Terry J. Reedy
Jul 18 '05 #2

"Terry Reedy" <tj*****@udel.edu> schrieb im Newsbeitrag
news:tp********************@comcast.com...

"Jeremy Fincher" <fi*******@osu.edu> wrote in message
news:bg**********@news.cis.ohio-state.edu...
Sometimes I find myself simply wanting the length of an iterator.


An iterator is a function/method that traverses (or possibly
generates) a seqeuence. The sequence has a length (actual or
potential) but the iterator does not.


Very well explained. There are lots of usefull generators with unlimited
sequences.

- random generators

- def achilles():
while 1
:N=1.
yield N
n=n/2

- def schoenberg():
cycle=range(12)
while 1:
shuffle(cycle)
for i in cycle:
yield i
There is no way to determined, whether such generartors will come to an
end - The Halting Problem for Turing Machines ;-)
Thus there will never be a safe len(iterator).

Kindly
Michael
Jul 18 '05 #3
Terry Reedy wrote:
An iterator is a function/method that traverses (or possibly
generates) a seqeuence. The sequence has a length (actual or
potential) but the iterator does not.
Even some sequences don't have a length; consider (Lisp terminology)
"improper lists," where the cdr points to a cell earlier in the list. Or
any class with a somehow non-terminating __len__.
Alternative: initialize six counters to 0. Scan list once and update
appropriate counter.
Yes, that works in this particular case, and is probably a superior
solution.
If you mean a c-coded counter (which would not be an iterator itself)
equivalent to the above, that could be done. Perhaps len() could be
upgraded/extended to accept an iterator and count when it can't get a
__len__ method to call. The main downside is that iterators are
sometimes destructive (run once only).
That's why I don't think such a change should be made to len(); *all*
iterators are destructive and len() silently destroying them doesn't seem
generally useful enough for the potential for mistake.
In the meanwhile, is this really a bottleneck for you? or merely the
'pity' of a program running in 1 sec when 0.1 is possible?


The whole of itertools really seems to exist because of the "pity" of taking
efficient iterators and turning them into lists in order to do any
significant manipulation of them. In that case, I would imagine the pity
of having to turn an interator into a sequence in order to determine the
length of the underlying sequence would be reason enough.

Jeremy

Jul 18 '05 #4
Michael Peuser wrote:
There is no way to determined, whether such generartors will come to an
end - The Halting Problem for Turing Machines ;-)
Thus there will never be a safe len(iterator).


But then, there's no way to determine whether any given class' __len__ will
terminate, so you've got the same problem with len.

Granted, it's more likely to manifest itself with iterators and ilen than
with sequences and len, but if it's really an issue, ilen could take an
optional "max" argument for declaring a counter ilen isn't to exceed.

Jeremy
Jul 18 '05 #5
Another solution could be to implement custom lenght methods. However I see
no graceful way to do it with the quite tricky implementation (yield is the
only hint!) of 2.3.

It would be definitly easy with 2.2 "by hand" function factories (def
iter(), def __next__()), just def len() in addition and find the fastest
implementation

Kindly
Michael

"Jeremy Fincher" <fi*******@osu.edu> schrieb im Newsbeitrag
news:bg**********@news.cis.ohio-state.edu...
Michael Peuser wrote:
There is no way to determined, whether such generartors will come to an
end - The Halting Problem for Turing Machines ;-)
Thus there will never be a safe len(iterator).
But then, there's no way to determine whether any given class' __len__

will terminate, so you've got the same problem with len.

Granted, it's more likely to manifest itself with iterators and ilen than
with sequences and len, but if it's really an issue, ilen could take an
optional "max" argument for declaring a counter ilen isn't to exceed.

Jeremy

Jul 18 '05 #6
"Jeremy Fincher"
Sometimes I find myself simply wanting the length of an iterator. For
example, to collect some (somewhat useless ;)) statistics about a program
of mine, I've got code like this:

objs = gc.get_objects()
classes = len([obj for obj in objs if inspect.isclass(obj)])
functions = len([obj for obj in objs if inspect.isroutine(obj)])
modules = len([obj for obj in objs if inspect.ismodule(obj)])
dicts = len([obj for obj in objs if type(obj) == types.DictType])
lists = len([obj for obj in objs if type(obj) == types.ListType])
tuples = len([obj for obj in objs if type(obj) == types.TupleType])

Now, obviously I can (and will, now that 2.3 is officially released :))
replace the list comprehensions with itertools.ifilter, but I need an
itertools.ilen to find the length of such iterators.

I can imagine such a need arises in more useful situations than this, but
this is the particular case that brought the need to mind.

The Python code is simple, obviously:

def ilen(iterator):
i = 0
for _ in iterator:
i += 1
return i

But it's a pity to use itertools' super-fast iterators and have to use slow,
raw Python to determine their length :)

For your application, it is not hard to build a itertools version:
import itertools
def countif(predicate, seqn): .... return sum(itertools.imap(predicate, seqn))
def isEven(x): .... return x&1 == 0
countif(isEven, xrange(1000000)) 500000
def isTuple(x): .... return type(x) == types.TupleType
tuples = countif(isTuple, objs)

Raymond Hettinger
Jul 18 '05 #7
On Thu, 07 Aug 2003 03:10:10 -0400, rumours say that Jeremy Fincher
<fi*******@osu.edu> might have written:
objs = gc.get_objects()
classes = len([obj for obj in objs if inspect.isclass(obj)])
functions = len([obj for obj in objs if inspect.isroutine(obj)])
modules = len([obj for obj in objs if inspect.ismodule(obj)])
dicts = len([obj for obj in objs if type(obj) == types.DictType])
lists = len([obj for obj in objs if type(obj) == types.ListType])
tuples = len([obj for obj in objs if type(obj) == types.TupleType])


Another way to count objects:

# code start
import types, gc

type2key = {
types.ClassType: "classes",
types.FunctionType: "functions",
types.MethodType: "functions",
types.ModuleType: "modules",
types.DictType: "dicts",
types.ListType: "lists",
types.TupleType: "tuples"
}

sums = {
"classes": 0, "functions": 0, "modules": 0, "dicts": 0,
"lists": 0, "tuples": 0
}

for obj in gc.get_objects():
try:
sums[type2key[type(obj)]] += 1
except KeyError:
pass
# code end

This code is intended to be <2.3 compatible.
--
TZOTZIOY, I speak England very best,
Microsoft Security Alert: the Matrix began as open source.
Jul 18 '05 #8
Christos "TZOTZIOY" Georgiou <tz**@sil-tec.gr> wrote in
news:98********************************@4ax.com:
Another way to count objects:

# code start
import types, gc

type2key = {
types.ClassType: "classes",
types.FunctionType: "functions",
types.MethodType: "functions",
types.ModuleType: "modules",
types.DictType: "dicts",
types.ListType: "lists",
types.TupleType: "tuples"
}

sums = {
"classes": 0, "functions": 0, "modules": 0, "dicts": 0,
"lists": 0, "tuples": 0
}

for obj in gc.get_objects():
try:
sums[type2key[type(obj)]] += 1
except KeyError:
pass
# code end


I'm just curious, why did you decide to map the types to strings instead of
just using the types themselves?
e.g.
import gc
sums = {}
for obj in gc.get_objects(): if type(obj) not in sums:
sums[type(obj)] = 1
else:
sums[type(obj)] += 1

for typ, count in sums.iteritems(): print typ.__name__, count
instance 525
tuple 4273
class 162
getset_descriptor 14
traceback 2
wrapper_descriptor 165
list 258
module 71
instance method 279
function 1222
weakref 18
dict 1647
method_descriptor 82
member_descriptor 75
frame 18


--
Duncan Booth du****@rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
Jul 18 '05 #9
Duncan Booth wrote:
I'm just curious, why did you decide to map the types to strings instead
of just using the types themselves?


So I can pluralize them in my output.

Jeremy

Jul 18 '05 #10
On Fri, 8 Aug 2003 10:02:39 +0000 (UTC), rumours say that Duncan Booth
<du****@NOSPAMrcp.co.uk> might have written:
I'm just curious, why did you decide to map the types to strings instead of
just using the types themselves?
e.g.
import gc
sums = {}
for obj in gc.get_objects():

if type(obj) not in sums:
sums[type(obj)] = 1
else:
sums[type(obj)] += 1


Just because the initial code treated functions and methods as same;
also to be output-friendly. I offered code with similar functionality,
only more concise, it wasn't code for my use :)
--
TZOTZIOY, I speak England very best,
Microsoft Security Alert: the Matrix began as open source.
Jul 18 '05 #11

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

Similar topics

1
by: Dan Williams | last post by:
Is there any interest in adding a "Haskellish" take function to itertools? I know its easy enough to roll my own, I've been using: take = lambda iter, n: which works, but I was wondering if...
6
by: Robert Brewer | last post by:
def warehouse(stock, factory=None): """warehouse(stock, factory=None) -> iavailable, iremainder. Iterate over stock, yielding each value. Once the 'stock' sequence is exhausted, the factory...
1
by: anton muhin | last post by:
Hello, everybody! Trying to solve the problem in the subj, I found that I miss some iterator-related tools. Mostly consequental application of the same function to some argument (if I'm not...
1
by: Steven Bethard | last post by:
Is there a reason that itertools.islice doesn't support None arguments for start and step? This would be handy for use with slice objects: >>> r = range(20) >>> s1 = slice(2, 10, 2) >>> s2 =...
18
by: Ville Vainio | last post by:
For quick-and-dirty stuff, it's often convenient to flatten a sequence (which perl does, surprise surprise, by default): ]]] -> One such implementation is at ...
21
by: Steven Bethard | last post by:
Jack Diederich wrote: > > itertools to iter transition, huh? I slipped that one in, I mentioned > it to Raymond at PyCon and he didn't flinch. It would be nice not to > have to sprinkle 'import...
41
by: rurpy | last post by:
The code below should be pretty self-explanatory. I want to read two files in parallel, so that I can print corresponding lines from each, side by side. itertools.izip() seems the obvious way to...
23
by: Mathias Panzenboeck | last post by:
I wrote a few functions which IMHO are missing in python(s itertools). You can download them here: http://sourceforge.net/project/showfiles.php?group_id=165721&package_id=212104 A short...
17
by: Raymond Hettinger | last post by:
I'm considering deprecating these two functions and would like some feedback from the community or from people who have a background in functional programming. * I'm concerned that use cases for...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...

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.