RE: Simple Recursive Generator Question

From: Robert Brewer (fumanchu_at_amor.org)
Date: 12/19/03


Date: Fri, 19 Dec 2003 11:50:27 -0800
To: <python-list@python.org>

Probably not what you meant, but one of the things you're missing is
that generators nullify the need for recursion in this case:

def big(mask):
    index = 0
    while True:
        if mask == 0:
            break
        if mask & 0x1:
            yield index
        index += 1
        mask = mask >> 1

>>> for x in big(0x16):
... print x
...
1
2
4

The generator saves you having to pass the "index" param recursively.
You save both object memory size (only one 'index' and one 'mask' object
and their bound names) and function-calling overhead (stack space).

Robert Brewer
MIS
Amor Ministries
fumanchu@amor.org

> -----Original Message-----
> From: MetalOne [mailto:jcb@iteris.com]
> Sent: Friday, December 19, 2003 11:14 AM
> To: python-list@python.org
> Subject: Simple Recursive Generator Question
>
>
> I am trying to write a generator function that yields the
> index position
> of each set bit in a mask.
> e.g.
> for x in bitIndexGenerator(0x16): #10110
> print x
> --> 1 2 4
>
>
> This is what I have, but it does not work.
> Changing yield to print, shows that the recursion works correctly.
>
> def bitIndexGenerator(mask, index=0):
> if mask == 0: return
> elif mask & 0x1: yield index
> bitIndexGenerator(mask >> 1, index+1)
>
> What am I missing?
> --
> http://mail.python.org/mailman/listinfo/python-list
>



Relevant Pages

  • Re: Help- Recursion v. Iter Speed comparison
    ... Recursion is usually slower than ... >> Would using a generator be faster than recursion? ... > def f1: ... list comprehension approach ...
    (comp.lang.python)
  • RE: bad generator performance
    ... Aside from the recursion question... ... To make it work I had to build a data tree - I used the files and ... the generator version takes about 1/4 of the time that the ... for iterator in: ...
    (comp.lang.python)
  • Re: bad generator performance
    ... I would assume the recursion is ... good idea to represent the bookmarks as a tree (with folders as internal ... the generator version takes about 1/4 of the time that the ...
    (comp.lang.python)
  • Re: What is the "functional" way of doing this?
    ... grand conclusions about the general speed of recursion etc. in Python from ... As soon as the size of the list increases the generator function ... Not especially surprising. ... naturally more expensive than a single function call. ...
    (comp.lang.python)
  • Re: wrapping diassembled code
    ... What is missing is the info about any data costants (and ... string constants) used, just as you discovered. ... In order to understand recursion you must first understand recursion. ...
    (comp.unix.programmer)