Skip to content

Instantly share code, notes, and snippets.

@kwatch
Created August 14, 2014 09:15
Show Gist options
  • Save kwatch/d4eaac1df4c86d1c3353 to your computer and use it in GitHub Desktop.
Save kwatch/d4eaac1df4c86d1c3353 to your computer and use it in GitHub Desktop.
問題4:入れ子になっているリストを、入れ子を外すような関数 flatten(arr) を定義してください。
# -*- coding: utf-8 -*-
##
## 問題4:入れ子になっているリストを、入れ子を外すような関数 flatten(arr) を定義してください。
## 例:
## nested = [1, [2, [3, 4], 5, [6]]]
## arr = flatten(nested)
## print(arr)
## #=> [1, 2, 3, 4, 5, 6]
##
def flatten(nested):
arr = []
_flatten(nested, arr)
return arr
def _flatten(nested, arr): # flatten()内の関数内関数にしてもよい (多少遅くなるが)
for x in nested:
if isinstance(x, list):
_flatten(x, arr)
else:
arr.append(x)
## test
if __name__ == '__main__':
nested = [1, [2, [3, 4], 5, [6]]]
expected = [1, 2, 3, 4, 5, 6]
assert flatten(nested) == expected
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment