Dharmit Shah wrote: > I am learning Python and yesterday I cam across a definition wherein I was > supposed to flatten a list recursively. I am getting the solution properly > but wanted to know if I can optimize the code further. > > #!/usr/bin/env python > new_list=[] > def flatten(num_list): > """ > >>> flatten([2, 9, [2, 1, 13, 2], 8, [2, 6]]) > [2, 9, 2, 1, 13, 2, 8, 2, 6] > >>> flatten([[9, [7, 1, 13, 2], 8], [7, 6]]) > [9, 7, 1, 13, 2, 8, 7, 6] > >>> flatten([[9, [7, 1, 13, 2], 8], [2, 6]]) > [9, 7, 1, 13, 2, 8, 2, 6] > >>> flatten([[5, [5, [1, 5], 5], 5], [5, 6]]) > [5, 5, 1, 5, 5, 5, 5, 6] > """ > global new_list > for i in num_list: > if type(i) == type([]): > new_list = flatten(i) > else: > new_list.append(i) > tmp = new_list > new_list=[] > return tmp > > if __name__=="__main__": > import doctest > doctest.testmod() > > PS - My knowledge of Python is still very basic and I am trying to dive into > it as deeper as I can. Solutions on Stackoverflow.com were beyond my > understandability.
Using doctest and getting a recursive function right don't strike me as basic. This is pretty good for a beginner. I'll second Peter Otten regarding the use of a global. It's best to avoid using globals whenever possible, not just for reentrancy, but for more readable and maintainable code. A function should be self-contained if possible. There's no reason you can't use a local variable in this code (and you only need one, not two), and the resulting code would be more readable. Regarding this line: if type(i) == type([]): This also works: if type(i) == list: But this is better: if isinstance(i, list): isinstance(obj, class) means "is obj an instance of class or a subtype of class", so it's more general. Does anyone see a way to do this with a list comprehension? I don't. Would be a neat hack if it can be done. -- Tom Zych / freethin...@pobox.com "Because if they didn't vote for a lizard," said Ford, "the wrong lizard might get in." -- DNA _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor