(Write a Python program) Write a recursive function flatten. The function accept
ID: 3814264 • Letter: #
Question
(Write a Python program)
Write a recursive function
flatten. The function accepts a deeply nested list xs and transforms it
into a single-level list. You do not know how deeply the list is nested.
Here are sample calls:
print(flatten([[10, 200], 300, 40]))
print(flatten([-5, [30, [10, 50]], -50]))
print(flatten([4, [10, 20], [180, 30], 40]))
print(flatten([10, [10, [300, 400]], [20, 30]]))
Here are the resutls:
[10, 200, 300, 40]
[-5, 30, 10, 50, -50]
[4, 10, 20, 180, 30, 40]
[10, 10, 300, 400, 20, 20]
You can use the built-in function type() to determine if an item is a list. For example, if x is [10, 20], then the expression type(x) == list evaluates to True. On the other hand, if x is 10, then
type(x) == list evaluates to False.
Explanation / Answer
>>>def flatten(lst):
return sum( ([x] if not isinstance(x, list) else flatten(x) // checks whether x is an instance in the for x in lst), [] ) list
>>>flatten([[10, 200], 300, 40])
>>>[10, 200, 300, 40]
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.