Skip to content

Instantly share code, notes, and snippets.

@d2207197
Last active August 29, 2015 14:06
Show Gist options
  • Save d2207197/577feb34053f06e26831 to your computer and use it in GitHub Desktop.
Save d2207197/577feb34053f06e26831 to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"metadata": {
"celltoolbar": "Slideshow",
"name": "",
"signature": "sha256:4951a9398336566126b4ce22d0a399a9fed01de4a5817616842dceff41199623"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "code",
"collapsed": false,
"input": [
"def flatten(nested):\n",
" flat = []\n",
" depth = 0\n",
" def flatten_in(nested, flat, depth):\n",
" print '{}flatten_in({}, {})'.format(depth*'\\t', nested, flat)\n",
" for i in nested:\n",
" if isinstance(i, list):\n",
" flatten_in(i, flat,depth+1)\n",
" else:\n",
" print '{}{}.append({})'.format((depth+1)*'\\t',flat,i)\n",
" flat.append(i)\n",
" print '{}-> {}'.format(depth*'\\t',flat) \n",
" return flat\n",
" flatten_in(nested, flat, depth)\n",
" return flat"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 41
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"flatten([[1,[[3],2]],1,[[3]]])\n"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"flatten_in([[1, [[3], 2]], 1, [[3]]], [])\n",
"\tflatten_in([1, [[3], 2]], [])\n",
"\t\t[].append(1)\n",
"\t\tflatten_in([[3], 2], [1])\n",
"\t\t\tflatten_in([3], [1])\n",
"\t\t\t\t[1].append(3)\n",
"\t\t\t-> [1, 3]\n",
"\t\t\t[1, 3].append(2)\n",
"\t\t-> [1, 3, 2]\n",
"\t-> [1, 3, 2]\n",
"\t[1, 3, 2].append(1)\n",
"\tflatten_in([[3]], [1, 3, 2, 1])\n",
"\t\tflatten_in([3], [1, 3, 2, 1])\n",
"\t\t\t[1, 3, 2, 1].append(3)\n",
"\t\t-> [1, 3, 2, 1, 3]\n",
"\t-> [1, 3, 2, 1, 3]\n",
"-> [1, 3, 2, 1, 3]\n"
]
},
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 42,
"text": [
"[1, 3, 2, 1, 3]"
]
}
],
"prompt_number": 42
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"!gist flatten.ipynb --update 577feb34053f06e26831"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"https://gist.github.com/577feb34053f06e26831\r\n"
]
}
],
"prompt_number": 33
},
{
"cell_type": "code",
"collapsed": false,
"input": [],
"language": "python",
"metadata": {},
"outputs": []
}
],
"metadata": {}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment