Flatten a nested list · Achatamento de lista aninhada
Flatten a nested list
A list can hold integers and other lists, nested to any depth: [1, [2, 3], [4, [5, 6]]]. Return one flat list of the integers in order: [1, 2, 3, 4, 5, 6].
Recursion fits perfectly. Loop over each item: if it's a list, flatten it and add the results; otherwise it's an integer, so add it directly. Use isinstance(item, list) to tell them apart.
Achatar uma lista aninhada
Uma lista pode segurar inteiros e outras listas, aninhadas a qualquer profundidade: [1, [2, 3], [4, [5, 6]]]. Devolva uma lista plana dos inteiros em ordem: [1, 2, 3, 4, 5, 6].
Recursão encaixa perfeitamente. Faça um loop sobre cada item: se for uma lista, achate ela e adicione os resultados; caso contrário é um inteiro, então adicione-o diretamente. Use isinstance(item, list) para diferenciá-los.
Write flatten(nested): given a list that may contain nested lists of integers (any depth), return a single flat list of the integers, in order. Use recursion. · Escreva flatten(nested): dado uma lista que pode conter listas aninhadas de inteiros (qualquer profundidade), retorne uma única lista plana dos inteiros, na ordem. Use recursão.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.