From d0fb9d3b9857fd63e8339f6d6d2a0b5d1d306875 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 3 Jan 2020 12:59:16 +0200 Subject: [PATCH] Update code in deep_flatten --- snippets/deep_flatten.md | 21 +++++---------------- 1 file changed, 5 insertions(+), 16 deletions(-) diff --git a/snippets/deep_flatten.md b/snippets/deep_flatten.md index 299855bbf..c92278691 100644 --- a/snippets/deep_flatten.md +++ b/snippets/deep_flatten.md @@ -6,25 +6,14 @@ tags: list,recursion,intermediate Deep flattens a list. Use recursion. -Define a function, `spread`, that uses either `list.extend()` or `list.append()` on each element in a list to flatten it. -Use `list.extend()` with an empty list and the `spread` function to flatten a list. -Recursively flatten each element that is a list. +Use `isinstance()` with `collections.abc.Iterable` to check if an element is iterable. +If it is, apply `deep_flatten()` recursively, otherwise return `[lst]`. ```py -def spread(arg): - ret = [] - for i in arg: - if isinstance(i, list): - ret.extend(i) - else: - ret.append(i) - return ret +from collections.abc import Iterable -def deep_flatten(lst): - result = [] - result.extend( - spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst)))) - return result +def deep_flatten(lst): + return [a for i in lst for a in deep_flatten(i)] if isinstance(lst, Iterable) else [lst] ``` ```py