{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Hàm" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Định nghĩa hàm" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hi\n" ] }, { "data": { "text/plain": [ "False" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def is_even(i):\n", " \"\"\"\n", " Input: i, a positive int\n", " Returns True if i is even, otherwise False\n", " \"\"\"\n", " print(\"hi\")\n", " return i % 2 == 0\n", "\n", "is_even(3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Bài tập\n", "\n", "Write a function isIn that accepts two strings as arguments and returns True if either string occurs anywhere in the other, and False otherwise. Hint: you might want to use the built-in str operation in." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Phạm vi của biến" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "in f(x): x = 4\n", "out f(x): x = 3\n" ] } ], "source": [ "def f( x ):\n", " x = x + 1\n", " print('in f(x): x =', x)\n", " return x\n", "\n", "x = 3\n", "z = f( x )\n", "print('out f(x): x =', x)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "NoneType" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def is_even( i ):\n", " i % 2 == 0\n", " \n", "a = is_even(3)\n", "type(a)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "inside func_a\n", "None\n", "inside func_b\n", "7\n", "inside func_c\n", "inside func_a\n", "None\n" ] } ], "source": [ "def func_a():\n", " print('inside func_a')\n", "def func_b(y):\n", " print('inside func_b')\n", " return y\n", "def func_c(z):\n", " print('inside func_c')\n", " return z()\n", "\n", "print(func_a())\n", "print(5 + func_b(2))\n", "print(func_c(func_a))" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "5\n" ] } ], "source": [ "def f(y):\n", " x = 1\n", " x += 1\n", " print(x)\n", "\n", "x = 5\n", "f(x)\n", "print(x)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n", "6\n", "5\n" ] } ], "source": [ "def g(y):\n", " print(x)\n", " print(x + 1)\n", " \n", "x = 5\n", "g(x)\n", "print(x)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "ename": "UnboundLocalError", "evalue": "local variable 'x' referenced before assignment", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mUnboundLocalError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mx\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m5\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0mh\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 6\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;32m\u001b[0m in \u001b[0;36mh\u001b[0;34m(y)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mh\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0my\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mx\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mx\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mx\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m5\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mh\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mUnboundLocalError\u001b[0m: local variable 'x' referenced before assignment" ] } ], "source": [ "def h(y):\n", " x = x + 1\n", " \n", "x = 5\n", "h(x)\n", "print(x)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "in g(x): x = 4\n" ] }, { "data": { "text/plain": [ "4" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def g(x):\n", " def h():\n", " x = 'abc'\n", " x = x + 1\n", " print('in g(x): x =', x)\n", " h()\n", " return x\n", "\n", "x = 3\n", "z = g(x)\n", "z" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Tham số đặt tên - Keyword Arguments" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Eric Grimson\n", "Eric Grimson\n", "Eric Grimson\n", "Eric Grimson\n" ] } ], "source": [ "def printName(firstName, lastName, reverse):\n", " if reverse:\n", " print(lastName + ', ' + firstName)\n", " else:\n", " print(firstName, lastName)\n", " \n", "printName('Eric', 'Grimson', False)\n", "\n", "printName('Eric', 'Grimson', reverse = False)\n", "\n", "printName('Eric', lastName = 'Grimson', reverse = False)\n", "\n", "printName(lastName = 'Grimson', firstName = 'Eric', reverse = False)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Giá trị mặc định - default values" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Eric Grimson\n", "Grimson, Eric\n" ] } ], "source": [ "def printName(firstName, lastName, reverse = False):\n", " if reverse:\n", " print(lastName + ', ' + firstName)\n", " else:\n", " print(firstName, lastName)\n", " \n", "printName('Eric', 'Grimson')\n", "\n", "printName('Eric', 'Grimson', True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Các đặt tả - specification/docstring" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hi\n" ] }, { "data": { "text/plain": [ "False" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def is_even( i ):\n", " \"\"\"\n", " Input: i, a positive int\n", " Returns True if i is even, otherwise False\n", " \"\"\"\n", " print('hi')\n", " return i % 2 == 0\n", "\n", "# hit Shift-Tab to see docstring\n", "is_even(3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Đệ qui" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def mult_iter(a, b):\n", " result = 0\n", " while b > 0:\n", " result += a\n", " b -= 1\n", " return result\n", " \n", "mult_iter(2, 3)" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def mult(a, b):\n", " if b == 1:\n", " return a\n", " else:\n", " return a + mult(a, b-1)\n", " \n", "mult(2, 3)" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "24" ] }, "execution_count": 49, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def fact(n):\n", " if n == 1:\n", " return 1\n", " else:\n", " return n*fact(n-1)\n", " \n", "fact(4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Towers of Hanoi\n", "\n", "[Video giới thiệu](https://youtu.be/rVPuzFYlfYE?t=1m20s)" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "move from P1 to P3\n", "move from P1 to P2\n", "move from P3 to P2\n", "move from P1 to P3\n", "move from P2 to P1\n", "move from P2 to P3\n", "move from P1 to P3\n", "move from P1 to P2\n", "move from P3 to P2\n", "move from P3 to P1\n", "move from P2 to P1\n", "move from P3 to P2\n", "move from P1 to P3\n", "move from P1 to P2\n", "move from P3 to P2\n" ] } ], "source": [ "def printMove(fr, to):\n", " print('move from ' + str(fr) + ' to ' + str(to))\n", " \n", "def Towers(n, fr, to, spare):\n", " if n == 1:\n", " printMove(fr, to)\n", " else:\n", " Towers(n - 1, fr, spare, to)\n", " Towers(1, fr, to, spare)\n", " Towers(n - 1, spare, to, fr)\n", " \n", "Towers(4, 'P1', 'P2', 'P3')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Đệ qui với nhiều trường hợp ngừng (base cases)" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "fib of 0 = 1\n", "fib of 1 = 1\n", "fib of 2 = 2\n", "fib of 3 = 3\n", "fib of 4 = 5\n", "fib of 5 = 8\n", "fib of 6 = 13\n", "fib of 7 = 21\n", "fib of 8 = 34\n", "fib of 9 = 55\n", "fib of 10 = 89\n" ] } ], "source": [ "def fib(x):\n", " \"\"\"\n", " assumes x an int >= 0\n", " return Fibonacci of x\n", " \"\"\"\n", " if x == 0 or x == 1:\n", " return 1\n", " else:\n", " return fib(x - 1) + fib(x - 2)\n", " \n", "def testFib(n):\n", " for i in range(n + 1):\n", " print('fib of', i, '=', fib(i))\n", " \n", "testFib(10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Bài tập\n", "\n", "When the implementation of fib in the above program is used to compute fib(5), how many times does it compute the value of fib(2) on the way to computing fib(5)?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " ## Đệ qui với phi số" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Try dogGod\n", "True\n", "Try Able was I, ere I saw Elba\n", "True\n" ] } ], "source": [ "def isPalindrome(s):\n", " def toChars(s):\n", " s = s.lower()\n", " ans = ''\n", " for c in s:\n", " if c in 'abcdefghijklmnopqrstuvwxyz':\n", " ans = ans + c\n", " return ans\n", " \n", " def isPal(s):\n", " if len(s) <= 1:\n", " return True\n", " else:\n", " return s[0] == s[-1] and isPal(s[1:-1])\n", " \n", " return isPal(toChars(s))\n", "\n", "def testIsPalindrome():\n", " print('Try dogGod')\n", " print(isPalindrome('dogGod'))\n", " print('Try Able was I, ere I saw Elba')\n", " print(isPalindrome(\"Able was I, ere I saw Elba\"))\n", " \n", "testIsPalindrome()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Tập tin" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [], "source": [ "# %load Files/circle.py\n", "pi = 3.14159\n", "\n", "def area(radius):\n", " return pi * (radius**2)\n", "\n", "def circumference(radius):\n", " return 2*pi*radius" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "3.14159\n", "28.27431\n", "18.849539999999998\n" ] } ], "source": [ "from Files import circle\n", "pi = 3\n", "print(pi)\n", "print(circle.pi)\n", "print(circle.area(3))\n", "print(circle.circumference(3))" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter name: man\n", "Enter name: le\n" ] } ], "source": [ "nameHandle = open('Files/kids', 'w')\n", "for i in range(2):\n", " name = input('Enter name: ')\n", " nameHandle.write(name + '\\n')\n", "nameHandle.close()" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "man\n", "\n", "le\n", "\n" ] } ], "source": [ "nameHandle = open('Files/kids', 'r')\n", "for line in nameHandle:\n", " print(line)\n", "nameHandle.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- - -\n", "[Trước: Các phương pháp cơ bản giải quyết bài toán trên máy tính](http://nbviewer.jupyter.org/github/manleviet/introCSusingPython/blob/master/3%20-%20C%C3%A1c%20ph%C6%B0%C6%A1ng%20ph%C3%A1p%20c%C6%A1%20b%E1%BA%A3n%20gi%E1%BA%A3i%20quy%E1%BA%BFt%20b%C3%A0i%20to%C3%A1n%20tr%C3%AAn%20m%C3%A1y%20t%C3%ADnh.ipynb) | \n", "[Mục lục](http://nbviewer.jupyter.org/github/manleviet/introCSusingPython/blob/master/index.ipynb) | \n", "[Tiếp: Tuple và List](http://nbviewer.jupyter.org/github/manleviet/introCSusingPython/blob/master/5%20-%20Tuple%2C%20List.ipynb)" ] } ], "metadata": { "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.6.4" } }, "nbformat": 4, "nbformat_minor": 2 }