Aug-12-2017, 01:15 AM
(Even though this is still Python, it's not really a question, or any other section, so here I am.)
I often give an interview question to flatten a nested structure, such as [1, 2, [3, [4]], 5]. To do it "greedily" it trivial for most people, but to do it "lazily" is often more of a challenge (especially in other languages). I received a solution like this recently:
Compare it to something like this
I'm curious what others thoughts' are on this, and please think about it a bit before checking the spoiler...
I often give an interview question to flatten a nested structure, such as [1, 2, [3, [4]], 5]. To do it "greedily" it trivial for most people, but to do it "lazily" is often more of a challenge (especially in other languages). I received a solution like this recently:
def flatten(a): for el in a: if type(el) == list: for el1 in flatten(el): yield el1 else: yield elUntil this week, this was basically the solution I always wanted. Sure, isinstance might be preferred, and yield from, and maybe you even want some way to handle iterables other than lists, but the gist of it is there. Right?
Compare it to something like this
def flatten(x): stack = [iter(x)] while stack: try: e = next(stack[-1]) except StopIteration: stack.pop() else: if isinstance(e, list): stack.append(iter(e)) else: yield eThat looks so noisy, right? The first one being definitely better?
I'm curious what others thoughts' are on this, and please think about it a bit before checking the spoiler...