diff --git a/README.md b/README.md index 742e5d7cd..d8320a352 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,33 @@ count_vowels('foobar') # 3 count_vowels('gym') # 0 ``` +### deepFlatten + +Deep flattens a list. + +Use recursion. Use `list.extend()` with an empty array (`result`) and the spread function to flatten a list. Recursively flatten each element that is a list. + +```python + +def spread(arg): + ret = [] + for i in arg: + if isinstance(i, list): + ret.extend(i) + else: + ret.append(i) + return ret + + def deep_flatten(arr): + result = [] + result.extend(spread(list(map(lambda x : deep(x) if type(x) == list else x,arr)))) + return result + +``` + +```python +deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5] +``` ### gcd Calculates the greatest common divisor between two or more numbers/lists. diff --git a/snippets/deep_flatten.md b/snippets/deep_flatten.md index 12649d150..e1842bb2d 100644 --- a/snippets/deep_flatten.md +++ b/snippets/deep_flatten.md @@ -4,7 +4,8 @@ Deep flattens a list. Use recursion. Use `list.extend()` with an empty array (`result`) and the spread function to flatten a list. Recursively flatten each element that is a list. -```python +```python + def spread(arg): ret = [] for i in arg: @@ -18,6 +19,7 @@ def spread(arg): result = [] result.extend(spread(list(map(lambda x : deep(x) if type(x) == list else x,arr)))) return result + ``` ```python