Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. from functools import reduce
  2.  
  3. '''
  4. flatten function takes one input parameter which may contains hierarchical list of integers and flatten to single dimesnion List.
  5.  
  6. First parameter of lambda function calls same function recursively if first element of array is list type
  7. ([a],flatten(a))[type(a) ==list]
  8.  
  9. Second parameter of lambda function calls same function recursively if second element of array is list type
  10. ([b],flatten(b))[type(b) ==list]
  11.  
  12. reduce function keep pulls the elements in array tills end and append to array
  13.  
  14. last part of code executes for least granular element
  15. if type(y) ==list and len(y)>1 else y
  16.  
  17. '''
  18. def flatten(y):
  19. return reduce(lambda a,b:([a],flatten(a))[type(a) ==list] +([b],flatten(b))[type(b) ==list],y) \
  20. if type(y) ==list and len(y)>1 else y
  21.  
  22.  
  23.  
  24. if __name__ == '__main__':
  25. try:
  26. l_arr_in = [1, [2, 3], [4, 5, 6], [7], [[8, 9], 9], 10, [20, 30, [40, [50, [60, [70, 80]]]]]]
  27. print(flatten(l_arr_in))
  28. except IndexError as e:
  29. print ("Error :--", e)
  30. except Exception as e:
  31. print ("Error :--", e)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement