Is there a Python module that already does this?

Emile van Sebille emile at fenx.com
Wed Feb 6 14:03:02 EST 2002


 "David Eppstein"
> Isn't all that list-copying (ary[1:]) going to make for a very
inefficient
> algorithm?

OK... this compares in timing to yours and doesn't depend on recursion
depth or generators:

def flatten(ary):
    try:
        if ary[0] == ary:rslt.append(ary)
        else:
            flatten(ary[0])
            flatten(ary[1:])
    except:
        if ary: rslt.append(ary)

rslt = []
flatten(("cat",5,['dog',[3,3,1]],"zoo"))
print '\n\n',rslt

I knew it was a stinker when I posted it, but I liked the deceiving
simplicity of the code.  ;-)

Apologies to all...

--

Emile van Sebille
emile at fenx.com

---------




More information about the Python-list mailing list