| Store | Cart

[Tutor] flattening a list

From: Gonšalo Rodrigues <op73...@mail.telepac.pt>
Thu, 13 Jan 2005 14:00:58
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

Recent Messages in this Thread
Chad Crabtree Jan 13, 2005 03:28 am
Danny Yoo Jan 13, 2005 07:15 am
Gonšalo Rodrigues Jan 13, 2005 02:00 pm
Messages in this thread