Guest User

Untitled

a guest
Jan 22nd, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3. mylist_regular = [[1, 2, [3]], 4]
  4. mylist_recursive = [[1, 2, [3]], 4]
  5.  
  6. # flatten a list of lists of integers, recursively
  7. # lst : list of integers
  8. # returns: a flattened list
  9. def flatten_recursive(lst):
  10. # return the current element if it's not a list, else call routine again with current list
  11. # initial value is empty list
  12. return sum(([x] if not isinstance(x, list) else flatten_recursive(x) for x in lst), [])
  13.  
  14.  
  15. # flatten a list of lists of integers, recursively
  16. # lst : list of integers, unpacked in positional params
  17. # returns: the next interger from the list
  18. def flatten_regular(*lst):
  19. for x in lst:
  20. print(x)
  21. if hasattr(x, '__iter__'):
  22. # if this is another list (it's iterable), unpack it and
  23. for y in flatten_regular(*x):
  24. # yield each value upon invocation
  25. yield y
  26. else:
  27. # if it's not iterable (not a list), yield the intermediate value
  28. yield x
  29.  
  30.  
  31. print(flatten_recursive(mylist_recursive))
  32. # convert the result back into a list
  33. print(list(flatten_regular(mylist_regular)))
Add Comment
Please, Sign In to add comment