Chad Crabtree wrote:
The only problem with this if it is to big or to deeply nested then
it will overflow the stack?



Danny Yoo has given a mind-blowing continuation implementation that will not overflow the stack. Below goes a recursive-iterator implementation. To avoid deep recursion the code can simluate its own stack (or hope that Python gains tail-call optimization *grin*) but for simplicity's sake we just use recursion.


def isIterable(iterable):
    """Test for iterable-ness."""
    try:
        iter(iterable)
    except TypeError:
        return False
    return True

def isBadIterable(iterable):
    """Return True if it's a 'bad' iterable.

Note: string's are bad because, when iterated they return strings making itterflatten loop infinitely.
"""
return isinstance(iterable, basestring)


def iterflatten(iterable):
    """Return a flattened iterator."""
    it = iter(iterable)
    for e in it:
        if isIterable(e) and not isBadIterable(e):
            #Recurse into iterators.
            for f in iterflatten(e):
                yield f
        else:
            yield e

A test:

for elem in iterflatten([1,
                         2,
                         [3, 4, (5, 6), 7],
                         8,
                         [9],
                         [10, 11, iter([12, 13])]]):
    print elem

And it gives:

>>> 1
2
3
4
5
6
7
8
9
10
11
12
13

Best regards,
G. Rodrigues
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to