# Problem 2 # # Write a function called flatten. The function is passed a parame
ID: 3836219 • Letter: #
Question
# Problem 2
#
# Write a function called flatten. The function is passed a parameter
# x, which may be a list (possibly containing embedded lists), or
# a non-list such as an integer. The function should
# return a list containing no embedded lists, and containing the
# items in x in the same order in which they appear in x.
# Your solution must be recursive and have no loops.
# For example:
#
# >>> flatten(1)
# [1]
# >>> flatten([1,2,3])
# [1, 2, 3]
# >>> flatten([[3, 1, 2], [[3, 6, 2], [6, 1, 0, 6]]]])
[3, 1, 2, 3, 6, 2, 6, 1, 0, 6]
# >>> flatten([[[[[[[[1]]]], 2]]]])
# [1, 2]
###############################################################
def flatten(x):
return [ ] # replace
Explanation / Answer
from collections import Iterable def flatten(items): for x in items: if isinstance(x, Iterable): yield from flatten(x) else: yield x list(flatten(l))
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.