Advertisement
Guest User

flatten

a guest
Apr 24th, 2023
592
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.12 KB | None | 0 0
  1. import itertools
  2. import unittest
  3. from collections.abc import Iterable
  4.  
  5.  
  6. def flatten(items):
  7.     if isinstance(items, Iterable):
  8.         yield from itertools.chain.from_iterable(flatten(item) for item in items)
  9.     else:
  10.         yield items
  11.  
  12.  
  13. class TestFlatten(unittest.TestCase):
  14.     def test_non_iterable(self):
  15.         # expect return a iterable contain 5
  16.         self.assertListEqual(list(flatten(5)), [5])
  17.  
  18.     def test_one_item(self):
  19.         self.assertListEqual(list(flatten([123])), [123])
  20.  
  21.     def test_1d(self):
  22.         self.assertListEqual(list(flatten([2, 3, 5, 7, 11])), [2, 3, 5, 7, 11])
  23.  
  24.     def test_2d(self):
  25.         self.assertListEqual(list(flatten([[2, 3], [5, 7, 11]])), [2, 3, 5, 7, 11])
  26.  
  27.     def test_3d(self):
  28.         self.assertListEqual(
  29.             list(flatten([[[2, 2], [3, 3]], [[5, 5], [7, 7]], [[11, 13, 17]]])),
  30.             [2, 2, 3, 3, 5, 5, 7, 7, 11, 13, 17],
  31.         )
  32.  
  33.     def test_mixed_dimension(self):
  34.         self.assertListEqual(
  35.             list(flatten([2, [3, 5], [7, [11, 13]]])), [2, 3, 5, 7, 11, 13]
  36.         )
  37.  
  38.  
  39. if __name__ == "__main__":
  40.     unittest.main()
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement