Advertisement
fkudinov

12. Flatten a List / Вирішуємо задачі на Python CheckIO Українською

Sep 17th, 2023
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | Source Code | 0 0
  1. # ----------   tasks/flatten.py   -----------
  2.  
  3.  
  4. def is_leaf(array):
  5.     return isinstance(array, int)
  6.  
  7.  
  8. def flat_list(array):
  9.     res = []
  10.  
  11.     for i in array:
  12.         if is_leaf(i):
  13.             res.append(i)
  14.         else:
  15.             leafs = flat_list(i)
  16.             res += leafs
  17.  
  18.     return res
  19.  
  20.  
  21. def flat_list_while(array):
  22.     res = []
  23.  
  24.     query = list(array)
  25.  
  26.     while query:
  27.         i = query.pop(0)
  28.         if is_leaf(i):
  29.             res.append(i)
  30.         else:
  31.             items = list(i)
  32.             query = items + query
  33.  
  34.     return res
  35.  
  36.  
  37.  
  38. # ------------  tests/test_flatten.py  -----------------
  39.  
  40. import pytest
  41.  
  42. from tasks.flatten import flat_list, flat_list_while
  43.  
  44.  
  45. @pytest.mark.parametrize("func", [flat_list, flat_list_while])
  46. @pytest.mark.parametrize(["data", "res"], [
  47.     [[], []],
  48.     [[1, 2, 3], [1, 2, 3]],
  49.     [[1, [2, 2, 2], 4], [1, 2, 2, 2, 4]],
  50.     [[[[2]], [4, [5, 6, [6], 6, 6, 6], 7]], [2, 4, 5, 6, 6, 6, 6, 6, 7]],
  51.     [[-1, [1, [-2], 1], -1], [-1, 1, -2, 1, -1]]
  52. ])
  53. def test_flatten(func, data, res):
  54.     assert func(data) == res
  55.  
Tags: checkio
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement