Skip to content

Instantly share code, notes, and snippets.

@dedsm
Created December 11, 2016 00:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dedsm/1bdf130fc2828a9f4ef355604e8f036f to your computer and use it in GitHub Desktop.
Save dedsm/1bdf130fc2828a9f4ef355604e8f036f to your computer and use it in GitHub Desktop.

Flatten any multi-level nested iterable, and return a new iterable.

Testing:

after installing the requirements, just run py.test tests.py, it will generate several test cases automatically

Example:

In [1]: from flatten import Flatten

In [2]: a = [[2,3,[4,5],6],7,8,[[2,3],[5,6]]]

In [3]: Flatten(a).to_list()
Out[3]: [2, 3, 4, 5, 6, 7, 8, 2, 3, 5, 6]
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from collections import Iterable
class Flatten(object):
"""
Iterable to flatten multi-level nested iterables
"""
def __init__(self, iterator):
self.iterator = iter(iterator)
def __iter__(self):
for value in self.iterator:
if isinstance(value, Iterable):
# Recurse if it's nested, could be rewritten to keep a heap
# and thus remove the recursion
yield from Flatten(value)
else:
yield value
def to_list(self):
"""Just to avoid devs having to do list(Flatten(iterable))"""
return list(self)
pytest
hypothesis
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from pprint import pprint as pp
from hypothesis import given, example
from hypothesis.strategies import lists, integers, recursive
from flatten import Flatten
nested_lists = recursive(lists(integers()), lambda children: lists(children) | children)
@given(alist=nested_lists)
def test_regular_list(alist):
flat = Flatten(alist).to_list()
for elem in flat:
assert isinstance(elem, int)
def test_fixed_example():
alist = [[2,3,[4,5],6],7,8,[[2,3],[5,6]]]
flat = Flatten(alist).to_list()
assert flat == [2,3,4,5,6,7,8,2,3,5,6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment