Many production pipelines need to transform hierarchical data into a linear representation and then reconstruct the original shape later. This shows up in model input preprocessing, feature engineering, and other areas. Given a nested structure, write functions to flatten it into a linear representation and then unflatten it back to its original shape.
Given a nested structure represented as a list, where each element can be either an integer or a list, write two functions:
flatten(nested_list): Flatten the nested list into a single list of integers.unflatten(flat_list, original_structure): Given a flattened list and the original structure, reconstruct the nested list.[1, [2, 3], 4, [5, [6, 7]]][1, 2, 3, 4, 5, 6, 7][1, 2, 3, 4, 5, 6, 7] and the original structure [1, [2, 3], 4, [5, [6, 7]]][1, [2, 3], 4, [5, [6, 7]]]python def flatten(nested_list): flat_list = [] for item in nested_list: if isinstance(item, list): flat_list.extend(flatten(item)) else: flat_list.append(item) return flat_list
python def unflatten(flat_list, original_structure): result = [] index = 0 for item in original_structure: if isinstance(item, list): result.append(unflatten(flat_list[index:index + len(item)], item)) index += len(item) else: result.append(flat_list[index]) index += 1 return result
This solution uses recursion for both functions. The flatten function iterates through the nested list and appends integers directly or recursively flattens sublists. The unflatten function reconstructs the nested structure by iterating through the original structure and using the corresponding elements from the flattened list.