Flatten a list: Difference between revisions
No edit summary |
|||
Line 1: | Line 1: | ||
{{task}} |
{{task}} |
||
Write a function to flatten the nesting in an arbitrary [[wp:List (computing)|list]] of values. Your |
Write a function to flatten the nesting recursively in an arbitrary [[wp:List (computing)|list]] of values. Your program should work on the equivalent of this list: |
||
[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] |
[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] |
||
Where the correct result would be the list: |
Where the correct result would be the list: |
Revision as of 19:19, 16 August 2009
You are encouraged to solve this task according to the task description, using any language you may know.
Write a function to flatten the nesting recursively in an arbitrary list of values. Your program should work on the equivalent of this list:
[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
C.f. Tree traversal
Python
Function flatten
is recursive:
<lang python>>>> def flatten(lst):
return sum( ([x] if type(x) is not list else flatten(x)
for x in lst), [] )
>>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] >>> flatten(lst) [1, 2, 3, 4, 5, 6, 7, 8]</lang>
Function flat is iterative and flattens the list in-place: <lang python>>>> def flat(lst): i=0 while i<len(lst): while True: try: lst[i:i+1] = lst[i] except (TypeError, IndexError): break i += 1
>>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] >>> flat(lst) >>> lst [1, 2, 3, 4, 5, 6, 7, 8]</lang>
Ruby
flatten
is a built-in method of Arrays
<lang ruby>flat = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []].flatten
p flat # => [1, 2, 3, 4, 5, 6, 7, 8]</lang>