I’m doing an exercise to flatten nested lists. The code works in console but it doesn’t work when its in a file. I have no idea what’s going on. 🙁
def flatten(nested):
"""
>>> flatten([2, 9, [2, 1, 13, 2], 8, [2, 6]])
[2, 9, 2, 1, 13, 2, 8, 2, 6]
>>> flatten([[9, [7, 1, 13, 2], 8], [7, 6]])
[9, 7, 1, 13, 2, 8, 7, 6]
>>> flatten([[9, [7, 1, 13, 2], 8], [2, 6]])
[9, 7, 1, 13, 2, 8, 2, 6]
>>> flatten([[5, [5, [1, 5], 5], 5], [5, 6]])
[5, 5, 1, 5, 5, 5, 5, 6]
"""
simple = []
for x in nested:
if type(x) == type([]):
for y in x:
simple.append(y)
else:
simple.append(x)
return simple
if __name__ == '__main__':
import doctest
doctest.testmod()
I first tried to solve this exercise recursively but decided to try it iterative first.
edit: When executed in the file it just prints out the original function argument
TIA
The problem is that your flatten function only flattens one level. The reason why doctest is printing out errors is because it is indeed erroring. They are not what you passed in.
You should investigate a recursive approach that instead of appending
y— you call flatten onyas well.if type(x) != type([])can be your base case.