mckabue commited on
Commit
9d4f942
·
verified ·
1 Parent(s): 26293fb

RE_UPLOAD-REBUILD-RESTART

Browse files
Files changed (1) hide show
  1. utils/flatten.py +34 -0
utils/flatten.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Iterable, Literal
2
+ import sys
3
+
4
+
5
+ def flatten(iterable: Iterable, depth = sys.maxsize, return_type: Literal['list', 'generator'] = 'list') -> list | Iterable:
6
+ """
7
+ Flatten a nested iterable up to a specified depth.
8
+
9
+ Args:
10
+ iterable (iterable): The iterable to be expanded.
11
+ depth (int, optional): The depth to which the iterable should be expanded.
12
+ Defaults to 1.
13
+ return_type (Literal['list', 'generator'], optional): The type of the return value.
14
+ Defaults to 'list'.
15
+ Yields:
16
+ The expanded elements.
17
+ """
18
+
19
+ def expand(item, current_depth=0):
20
+ if current_depth == depth:
21
+ yield item
22
+ elif isinstance(item, (list, tuple, set)):
23
+ for sub_item in item:
24
+ yield from expand(sub_item, current_depth + 1)
25
+ else:
26
+ yield item
27
+
28
+ def generator():
29
+ for item in iterable:
30
+ yield from expand(item)
31
+
32
+ if return_type == 'list':
33
+ return list(generator())
34
+ return generator()