{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Python Basics"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Numbers"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"2 + 2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"50 - 5*6"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"(50 - 5*6) / 4"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"8 / 5 # division always return float number"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"8 // 5 # floor division discards the fractional part"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"17 % 3 # the % operator returns the remainder of the division"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [],
"source": [
"5 ** 2 # 5 squared"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"2 ** 7 # 2 to the power of 7"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"3 * 3.75 / 1.5 # would convert int to float"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## String"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"'SCAD is fun' ## single quotes\n",
"\"I love social computing\" ## double quotes\n",
"'doesn\\'t' ## use \\ to escape\n",
"\"doesn't\" ## or use double quotes instead"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"#### If you don’t want characters prefaced by \\ to be interpreted as special characters, you can use raw strings by adding an r before the first quote:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print(r'\\\\\\\\\\\\\\\\')\n",
"print('\\\\\\\\\\\\\\\\')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [],
"source": [
"print(\"\"\"\\\n",
"I'm a long paragraph.\n",
"This is the second line.\n",
"This is the third line.\n",
"\"\"\") \n",
"## Use triple quotes (\"\"\"...\"\"\" or '''...''') to wrap multiple lines of string, use \\ to omit newline.\n",
"print(\"\"\"\\\n",
"Hello\\\n",
"Hihi\n",
"\"\"\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [],
"source": [
"2*'hi' + '! Everyone!' ## Strings could be concatenated with +, and repeated with *"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"print('py''thon') ## Strings next to each other would be automatically concatenated\n",
"print(\"I'm a long paragraph.\"\n",
" \"This is the second line.\") \n",
"print(\"\"\"I'm a long paragraph.\n",
" This is the second line.\"\"\") \n",
"## There are small differences between these two ways."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [],
"source": [
"word = \"SCAD\" ## Strings can be indexed\n",
"print(word[0])\n",
"print(word[1])\n",
"print(word[2])\n",
"print(word[3])\n",
"print(word[-1])\n",
"print(word[-2])\n",
"print(word[-3])\n",
"print(word[-4])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"print(word[:2]) # character from the beginning to position 2 (excluded)\n",
"print(word[1:3]) # characters from position 0 (included) to 2 (excluded)\n",
"print(word[-2:]) # characters from the second-last (included) to the end"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"word[0] = 'D' # Python strings cannot be changed — they are immutable. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [],
"source": [
"## String build-in Methods\n",
"s = \"Social Computing Application Design!!!\"\n",
"print(len(s))\n",
"print(s.strip(\"!\")) ## default to remove leading and trailing whitespaces\n",
"print(s.lower())\n",
"print(s.split()) ## default "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## List"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"l = [1, 2, 3, 4, 5] ## new list with initial value\n",
"l = [] ## empty list"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"l = [1]*3 + [3, 4, 5] ## Lists could also be concatenated with +, and repeated with *\n",
"print(l)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"l = [1, 2, 3, 4, 5]\n",
"print(l[1:4])\n",
"print(l[:-2])\n",
"print(l[3:])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [],
"source": [
"## lists are mutable types\n",
"l = [1, 2, 3, 4, 5]\n",
"l[0] = 0\n",
"print(l)\n",
"l[1:3] = [2] ## you can replace any part of the list and the length would be different\n",
"print(l)\n",
"l[1:3] = [] ## you can even remove part of the list\n",
"print(l)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"l = [[1, 2], [3, 4]] ## multi-dimentional list\n",
"print(l[0])\n",
"print(l[0][0])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [],
"source": [
"## list build-in function\n",
"l = [1, 2, 3, 4, 5]\n",
"ll = l[:] ## shallow copy a list\n",
"l.append('SC')\n",
"ll.extend('AD')\n",
"print(l, ll)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"l = [1, 2, 2, 3, 3, 3]\n",
"print(l.count(1), l.count(2), l.count(5))"
]
},
{
"cell_type": "code",
"execution_count": 77,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3, 5, 6]\n",
"[1, 2, 3, 4, 6] [3, 1, 2, 6, 4]\n",
"[4, 6, 2, 1, 3]\n"
]
}
],
"source": [
"l = [5, 6, 1, 2, 3]\n",
"l.sort()\n",
"print(l)\n",
"ll = [3, 1, 2, 6, 4]\n",
"print(sorted(ll), ll) ## sorted would retun a new list with sorted value\n",
"ll.reverse()\n",
"print(ll)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Tuple"
]
},
{
"cell_type": "code",
"execution_count": 89,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(12345, 54321, 'hello!') 12345\n"
]
},
{
"ename": "TypeError",
"evalue": "'tuple' object does not support item assignment",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-89-320716d5b210>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0mt\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m12345\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m54321\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'hello!'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mt\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mt\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0mt\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m23456\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m: 'tuple' object does not support item assignment"
]
}
],
"source": [
"## Tuple is \"immutable\" list, you couldn't modify the elements you store in it\n",
"## A tuple consists of a number of values separated by commas \n",
"t = 12345, 54321, 'hello!'\n",
"print(t, t[0])\n",
"t[0] = 23456 ## you couldn't modify it!!"
]
},
{
"cell_type": "code",
"execution_count": 91,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"([1, 2, 3], [4, 5, 6])\n",
"([1, 3, 3], [4, 5, 6])\n"
]
}
],
"source": [
"t = [1, 2, 3], [4, 5, 6] ## You can store mutable objects in it\n",
"print(t)\n",
"t[0][1] = 3 ## And you can modify the mutable objects\n",
"print(t)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Packing and Unpacking"
]
},
{
"cell_type": "code",
"execution_count": 94,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Alice 12 Python\n"
]
}
],
"source": [
"t = 'Alice', 12, 'Python' ## This is called tuple packing\n",
"name, age, skills = t ## This is called tuple unpacking\n",
"print(name, age, skills)"
]
},
{
"cell_type": "code",
"execution_count": 95,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Alice 12 Python\n"
]
}
],
"source": [
"l = ['Alice', 12, 'Python']\n",
"name, age, skills = l ## You can also do list unpacking\n",
"print(name, age, skills)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Control Flow"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"x = int(input(\"input a number: \"))\n",
"if x < 0:\n",
" x = 0\n",
" print('Negative changed to zero')\n",
"elif x == 0:\n",
" print('Zero')\n",
"elif x == 1:\n",
" print('Single')\n",
"else:\n",
" print('More')"
]
},
{
"cell_type": "code",
"execution_count": 73,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2\n"
]
}
],
"source": [
"## online if else (like a > b? a : b in other languages)\n",
"a, b = 1, 2\n",
"print(a) if a > b else print(b)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [],
"source": [
"words = ['cat', 'window', 'defenestrate']\n",
"for w in words:\n",
" print(w, len(w))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"## WARNING - if you want to modify a list through a loop, you should iterate through a copy of the list\n",
"words = ['cat', 'window', 'defenestrate']\n",
"for w in words:\n",
" if len(w) > 6:\n",
" words.append(w) ## THE LOOP NEVER ENDS!"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['cat', 'window', 'defenestrate', 'defenestrate']\n"
]
}
],
"source": [
"words = ['cat', 'window', 'defenestrate']\n",
"for w in words[:]:\n",
" if len(w) > 6:\n",
" words.append(w)\n",
"print(words)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n",
"2\n",
"3\n",
"4\n"
]
}
],
"source": [
"## range() function is useful to iterate through numbers\n",
"for i in range(5):\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"3\n",
"5\n",
"7\n",
"9\n"
]
}
],
"source": [
"for i in range(1, 11, 2):\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0 cat\n",
"1 window\n",
"2 defenestrate\n"
]
}
],
"source": [
"## enumerate() - iterate through a iterable with index\n",
"words = ['cat', 'window', 'defenestrate']\n",
"for i, w in enumerate(words):\n",
" print(i, w)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"### `break` and `continue` are the same as in C, Java"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## List Comprehension\n",
"### A more consise and readable way to create list"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 4, 9, 16, 25]\n"
]
}
],
"source": [
"## create a list with loop\n",
"squares = []\n",
"for i in range(1, 6):\n",
" squares.append(i**2)\n",
"print(squares)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"[1, 4, 9, 16, 25]"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"## with list comprehension\n",
"[i ** 2 for i in range(1, 6)]"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"[1, 4, 9, 16, 25]"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"## if you like functional programming and you're familiar with map() function\n",
"list(map(lambda i: i ** 2, range(1, 6)))"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]\n"
]
}
],
"source": [
"## combine two list with loop\n",
"comb = []\n",
"for x in [1, 2 ,3]:\n",
" for y in [1, 2, 3]:\n",
" if x != y:\n",
" comb.append((x, y))\n",
"print(comb)"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]"
]
},
"execution_count": 48,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"## with list comprehension\n",
"[(x, y) for x in [1, 2, 3] for y in [1, 2, 3] if x != y]"
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"[1, 2, 3, 4, 5, 6, 7, 8, 9]"
]
},
"execution_count": 52,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"## flatten nested list\n",
"vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n",
"[num for row in vec for num in row]"
]
},
{
"cell_type": "code",
"execution_count": 53,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]\n"
]
}
],
"source": [
"## transpose the matrix\n",
"matrix = [\n",
" [1, 2, 3, 4],\n",
" [5, 6, 7, 8],\n",
" [9, 10, 11, 12],\n",
"]\n",
"new_matrix = []\n",
"for i in range(4):\n",
" new_row = []\n",
" for row in matrix:\n",
" new_row.append(row[i])\n",
" new_matrix.append(new_row)\n",
"print(new_matrix)"
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]\n"
]
}
],
"source": [
"## list comprehension\n",
"matrix = [\n",
" [1, 2, 3, 4],\n",
" [5, 6, 7, 8],\n",
" [9, 10, 11, 12],\n",
"]\n",
"new_matrix = []\n",
"for i in range(4):\n",
" new_matrix.append([row[i] for row in matrix])\n",
"print(new_matrix)"
]
},
{
"cell_type": "code",
"execution_count": 56,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]\n"
]
}
],
"source": [
"## nested list comprehension\n",
"matrix = [\n",
" [1, 2, 3, 4],\n",
" [5, 6, 7, 8],\n",
" [9, 10, 11, 12],\n",
"]\n",
"print([[row[i] for row in matrix] for i in range(4)])"
]
},
{
"cell_type": "code",
"execution_count": 60,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]\n"
]
}
],
"source": [
"## Advanced!! In this case, we should use build in function: zip()\n",
"matrix = [\n",
" [1, 2, 3, 4],\n",
" [5, 6, 7, 8],\n",
" [9, 10, 11, 12],\n",
"]\n",
"print(list(zip(*matrix)))"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Dictionaries"
]
},
{
"cell_type": "code",
"execution_count": 64,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4098\n"
]
}
],
"source": [
"## Dictionary is like HashMap in Java, which stores key: value pairs\n",
"## keys could be any immutable types: string, number, and tuple(with only immutable types in it)\n",
"tel = {'jack': 4098, 'sape': 4139}\n",
"print(tel['jack'])"
]
},
{
"cell_type": "code",
"execution_count": 69,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"23\n",
"1\n"
]
}
],
"source": [
"## tuple could also be keys\n",
"tel = {(1, 2): 23}\n",
"print(tel[(1, 2)])\n",
"bigram = {('I', 'am'): 1, (\"you\", \"are\"): 2}\n",
"print(bigram[('I', 'am')])"
]
},
{
"cell_type": "code",
"execution_count": 130,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[('you', 'are'), ('I', 'am')]\n",
"[('I', 'am'), ('you', 'are')]\n",
"[(('you', 'are'), 2), (('I', 'am'), 5)]\n"
]
}
],
"source": [
"## Performing list(d.keys()) on a dictionary returns a list of all the keys used in the dictionary\n",
"bigram = {('I', 'am'): 5, (\"you\", \"are\"): 2}\n",
"print(list(bigram.keys()))\n",
"print(sorted(bigram.keys()))\n",
"\n",
"from operator import itemgetter\n",
"print(sorted(bigram.items(), key=itemgetter(1))) ## If you want to sort the dictionary with value"
]
},
{
"cell_type": "code",
"execution_count": 79,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n",
"False\n"
]
}
],
"source": [
"## use in, not in to check whether the key exist\n",
"bigram = {('I', 'am'): 1, (\"you\", \"are\"): 2}\n",
"print(('I', 'am') in bigram)\n",
"print(('so', 'cool') in bigram)"
]
},
{
"cell_type": "code",
"execution_count": 81,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"('you', 'are') 2\n",
"('I', 'am') 1\n"
]
}
],
"source": [
"## loop through dictionaries\n",
"bigram = {('I', 'am'): 1, (\"you\", \"are\"): 2}\n",
"for k, v in bigram.items():\n",
" print(key, value)"
]
},
{
"cell_type": "code",
"execution_count": 96,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"ename": "KeyError",
"evalue": "('so', 'cool')",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-96-9bfbcae6b2a7>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m## You would get error if you accessed non-exist keys in dictionary\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mbigram\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m{\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'I'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'am'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;34m\"you\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m\"are\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m}\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mbigram\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'so'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'cool'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mKeyError\u001b[0m: ('so', 'cool')"
]
}
],
"source": [
"## You would get error if you accessed non-exist keys in dictionary\n",
"bigram = {('I', 'am'): 1, (\"you\", \"are\"): 2}\n",
"print(bigram[('so', 'cool')])"
]
},
{
"cell_type": "code",
"execution_count": 99,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"None\n",
"No such key\n"
]
}
],
"source": [
"## You should use dict.get() in such case if you're not sure whether the key exist or not\n",
"bigram = {('I', 'am'): 1, (\"you\", \"are\"): 2}\n",
"print(bigram.get(('so', 'cool')))\n",
"print(bigram.get(('so', 'cool'), 'No such key')) ## you can set default answer as well"
]
},
{
"cell_type": "code",
"execution_count": 104,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[('blue', [2, 4]), ('yellow', [1, 3]), ('red', [1])]\n"
]
}
],
"source": [
"## Or, you can use defaultdict to handle this\n",
"from collections import defaultdict\n",
"s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]\n",
"d = defaultdict(list) ## the value we are going to store is list\n",
"for k, v in s:\n",
" d[k].append(v) ## if the key dosen't exist in the dictionary, a new entry would automatically create.\n",
"print(list(d.items()))"
]
},
{
"cell_type": "code",
"execution_count": 106,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[('s', 4), ('p', 2), ('i', 4), ('m', 1)]\n"
]
}
],
"source": [
"from collections import defaultdict\n",
"s = \"mississippi\"\n",
"d = defaultdict(int)\n",
"for character in s:\n",
" d[character] += 1\n",
"print(list(d.items()))"
]
},
{
"cell_type": "code",
"execution_count": 107,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"dict_items([('s', 4), ('p', 2), ('i', 4), ('m', 1)])\n"
]
}
],
"source": [
"## If you want to count something in the iterable objects, you could also try Counter\n",
"from collections import Counter\n",
"counter = Counter(\"mississippi\")\n",
"print(list(counter.items()))\n",
"## You can check more useful functions in \n",
"## https://docs.python.org/3/library/collections.html?highlight=collections#collections.Counter"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Function"
]
},
{
"cell_type": "code",
"execution_count": 113,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"89"
]
},
"execution_count": 113,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def fib(n): \n",
" if n < 2: return 1\n",
" return fib(n-1) + fib(n-2)\n",
"fib(10)"
]
},
{
"cell_type": "code",
"execution_count": 117,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Do you really want to quit?y\n",
"OK to overwrite the file?y\n",
"OK to overwrite the file?kll\n",
"Come on, only yes or no!\n",
"OK to overwrite the file?y\n"
]
},
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 117,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"## you can set default arguments as well!\n",
"def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):\n",
" while True:\n",
" ok = input(prompt)\n",
" if ok in ('y', 'ye', 'yes'):\n",
" return True\n",
" if ok in ('n', 'no', 'nop', 'nope'):\n",
" return False\n",
" retries = retries - 1\n",
" if retries < 0:\n",
" raise OSError('uncooperative user')\n",
" print(complaint)\n",
"ask_ok('Do you really want to quit?')\n",
"ask_ok('OK to overwrite the file?', 2)\n",
"ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')"
]
},
{
"cell_type": "code",
"execution_count": 119,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1]\n",
"[1, 2]\n",
"[1, 2, 3]\n"
]
}
],
"source": [
"## IMPORTANT!! - The default value is evaluated only once. (when the function first created)\n",
"## This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes.\n",
"def f(a, L=[]):\n",
" L.append(a)\n",
" return L\n",
"\n",
"print(f(1))\n",
"print(f(2))\n",
"print(f(3))"
]
},
{
"cell_type": "code",
"execution_count": 123,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Alice 10\n"
]
}
],
"source": [
"## You can return multiple value!\n",
"def f():\n",
" return (\"Alice\", 10)\n",
"name, age = f()\n",
"print(name, age)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## File I/O"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"## Read file\n",
"f = open(filename, 'r')\n",
"content = f.read() ## This would read the entire file\n",
"file.close() ## Remember to close the file!! \n",
"\n",
"## Write file\n",
"f = open(filename, 'w')\n",
"f.write('content')\n",
"file.close()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"## For reading lines from a file, you can loop over the file object. \n",
"## This is memory efficient, fast, and leads to simple code\n",
"for line in f:\n",
" print(line)\n",
"f.close()\n",
"## Or you can use f.readlines() to read all the lines of a file into a list"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"## GOOD!!!! To read/write the file within a block\n",
"with open(fliename, 'r') as f:\n",
" content = f.readlines()\n",
"## The file would automatically close!"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true,
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Print"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"print() ##print a newline"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"print(\"hello\") "
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1 ;2 ;3 ;4 ;5\n"
]
}
],
"source": [
"print(*[1, 2, 3, 4, 5], sep=' ;') ##print a list, and seperate by semicolon"
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"('b', 2)\n",
"('a', 1)\n",
"('b', 2)\n",
"('a', 1)\n"
]
}
],
"source": [
"dic = {'a': 1, 'b': 2}\n",
"print(*[item for item in dic.items()], sep='\\n') ##print dictionary\n",
"\n",
"for item in dic.items(): ##another way to print dictionary\n",
" print(item, sep=' ,')"
]
},
{
"cell_type": "code",
"execution_count": 86,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hao-Chuan is a professor.\n",
"Hiraku is a phD student.\n"
]
}
],
"source": [
"## print with format\n",
"dic = {'Hao-Chuan': 'professor', 'Hiraku': 'phD student'}\n",
"for k, v in dic.items():\n",
" print('{} is a {}.'.format(k, v))"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Assignment Hint"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## References\n",
"[python official documentation](https://docs.python.org/3/index.html) <br>\n",
"[python 慣用語] (http://seanlin.logdown.com/posts/206973-python-idioms-1) <br>\n",
"[python2 vs python3] (http://www.diveintopython3.net/porting-code-to-python-3-with-2to3.html)"
]
}
],
"metadata": {
"celltoolbar": "Slideshow",
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.0"
}
},
"nbformat": 4,
"nbformat_minor": 0
}