Created
July 25, 2016 17:01
-
-
Save djinn/6d6bf1eb0a949ea7c8e10109f555b1b6 to your computer and use it in GitHub Desktop.
Flatten list without using stdlib function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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