0
Python function
Write a Python function flatten(l) that takes a nonempty list of lists and returns a simple list of all the elements in the nested lists, flattened out. You can make use of the following function that returns True if its input is of type list. def listtype(l): return(type(l) == type([])) Here are some examples to show how flatten(l) should work. >>> flatten([1,2,[3],[4,[5,6]]]) [1, 2, 3, 4, 5, 6] >>> flatten([1,2,3,(4,5,6)]) [1, 2, 3, (4, 5, 6)]
2 ответов
+ 2
This is a work for recursion
lst = [1,2,[3],[4,[5,6]],7]
res = []
def flatlst(arr):
for elem in arr:
if type(elem) == type([]):
flatlst(elem)
else:
res.append(elem)
return res
print(flatlst(lst))
>>>>[1, 2, 3, 4, 5, 6, 7]
Next time try to code yourself at least a little bit. Asking others to do your homework is not a good move.
0
I tried it out. But I didn't get output for a test case. That's why I asked it here