Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from functools import reduce
- '''
- flatten function takes one input parameter which may contains hierarchical list of integers and flatten to single dimesnion List.
- First parameter of lambda function calls same function recursively if first element of array is list type
- ([a],flatten(a))[type(a) ==list]
- Second parameter of lambda function calls same function recursively if second element of array is list type
- ([b],flatten(b))[type(b) ==list]
- reduce function keep pulls the elements in array tills end and append to array
- last part of code executes for least granular element
- if type(y) ==list and len(y)>1 else y
- '''
- def flatten(y):
- return reduce(lambda a,b:([a],flatten(a))[type(a) ==list] +([b],flatten(b))[type(b) ==list],y) \
- if type(y) ==list and len(y)>1 else y
- if __name__ == '__main__':
- try:
- l_arr_in = [1, [2, 3], [4, 5, 6], [7], [[8, 9], 9], 10, [20, 30, [40, [50, [60, [70, 80]]]]]]
- print(flatten(l_arr_in))
- except IndexError as e:
- print ("Error :--", e)
- except Exception as e:
- print ("Error :--", e)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement