#C12415. Flatten Nested List
Flatten Nested List
Flatten Nested List
Given a nested list of integers that can be nested arbitrarily deep, your task is to flatten the list into a single list of integers. The order of the integers in the flattened list should be the same as their order of appearance when traversing the nested list from left to right.
For example, if the input nested list is:
[1, [2, [3, 4], 5], [6, 7]]
the output should be:
1 2 3 4 5 6 7
Note: You must implement a solution that reads input from stdin
and writes the result to stdout
. The input will be provided in a format that follows Python list syntax (which is similar to JSON array format). In your solution, you might find it useful to use recursion.
The underlying logic can be understood via the following recursive function description:
\(\text{flatten}(\text{lst}) = \begin{cases} \text{concat}(\text{flatten}(x)) & \text{if } x \text{ is a list} \\ x & \text{if } x \text{ is an integer} \end{cases}\)
inputFormat
The input is given as a single line from stdin
that represents the nested list. The list is formatted using brackets [ ]
, commas, and integers. For example:
[1, [2, [3, 4], 5], [6, 7]]
outputFormat
The output should be the flattened list printed as a sequence of integers separated by a single space on one line, written to stdout
.
[1, 2, 3]
1 2 3