Skip to content

Instantly share code, notes, and snippets.

@djinn
Created July 25, 2016 17:01
Show Gist options
  • Save djinn/6d6bf1eb0a949ea7c8e10109f555b1b6 to your computer and use it in GitHub Desktop.
Save djinn/6d6bf1eb0a949ea7c8e10109f555b1b6 to your computer and use it in GitHub Desktop.
Flatten list without using stdlib function
import unittest
def flatten(l):
collect = []
# make user l is iterable of some sort and not a dictionary
if hasattr(l, '__iter__') and not isinstance(l, dict):
for e in l:
print e
print flatten(e)
collect += flatten(e)
else:
collect.append(l)
return collect
class TestFlatten(unittest.TestCase):
def testSimple(self):
self.assertEqual(flatten([1,2,3,[4]]), [1,2,3,4])
def testSingle(self):
self.assertEqual(flatten(0), [0])
def testMapinList(self):
self.assertEqual(flatten([1, [{'m':'m'}]]), [1, {'m':'m'}])
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment