{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 函式 - Functions" ] }, { "cell_type": "markdown", "metadata": { "id": "DfxkgDhjseNg" }, "source": [ "本章節內容大綱\n", "* [函式 Function](#函式-Function)\n", "* [匿名函式 Lambda Function](#匿名函式-Lambda-Function)\n", "* [產生器 Generator](#產生器-Generator)\n", "* [星號,args 和 kargs](#星號-args-kargs)" ] }, { "cell_type": "markdown", "metadata": { "id": "c75Y792JseNh" }, "source": [ "## 函式 Function" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "DIghQmm5seNh", "outputId": "11697eb8-0cea-4d15-d25e-e648c5d30040" }, "outputs": [], "source": [ "'''\n", " def function_name(parameters):\n", " 'function docstring'\n", " do something\n", " return something\n", "'''" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "vXcFP5lNseNj" }, "outputs": [], "source": [ "# 什麼事都沒有做的 function\n", "def do_nothing():\n", " pass" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "do_nothing()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "I0z4IVPjseNj" }, "outputs": [], "source": [ "# 沒有參數/回傳值的,純粹執行一些事情的 function\n", "def say_hello():\n", " print(f'hello!')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Mj0BVefKseNj", "outputId": "f6e2be01-5a6a-4832-90e6-c0664567ae0f" }, "outputs": [], "source": [ "say_hello()\n", "say_hello()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 沒有參數,但有回傳值的 function\n", "def three():\n", " return 3" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "h9vjWKOOseNk", "outputId": "9bfb6420-4729-4737-81aa-775266cee61e" }, "outputs": [], "source": [ "print(5 + three())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 有參數/回傳值的 function\n", "def add(a, b):\n", " print(f'a = {a}, b = {b}')\n", " return a + b" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "9fDZEClEseNl", "outputId": "06ff637f-d4af-41e7-a9f7-1749c0164c01" }, "outputs": [], "source": [ "print(add(10, 8))" ] }, { "cell_type": "markdown", "metadata": { "id": "AUNa91SoseNm" }, "source": [ "## 匿名函式 Lambda Function" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "'''\n", "function_name = lambda input : calculation or output\n", "'''\n", "\n", "f = lambda x: x ** 2" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(f(4))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "f = lambda x, y: x**2 + 2*x*y + y**2" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(f(5,5))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "SFvJrSqRseNm", "outputId": "6371e929-d747-471b-9505-d9862dfbbc3a" }, "outputs": [], "source": [ "f = lambda x: [i*i for i in range(0, x+1)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "sg43LMkSseNn", "outputId": "21d0814b-99af-43a8-abfb-91b434537563" }, "outputs": [], "source": [ "print(f(10))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "f = lambda s: s.upper() + '!'" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(f('hello'))" ] }, { "cell_type": "markdown", "metadata": { "id": "xWjpdhh8seNn" }, "source": [ "## 產生器 Generator" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def simpleFunction():\n", " return 1 # return 完 記憶會清空,下次呼叫此函式時會從頭跑\n", " return 2 # 所以這行永遠不會被執行到" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(simpleFunction())\n", "print(simpleFunction())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def simpleGenerator():\n", " yield 1 # yield 完 記憶不會清空,下次呼叫此函式時會從下一行開始跑\n", " yield 2 # 第二次進入此函式時就會從這裡開始" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(simpleGenerator())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "g1 = simpleGenerator()\n", "print(next(g1))\n", "print(next(g1))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "zWMOMkwOseNn" }, "outputs": [], "source": [ "def randomGenerator(N):\n", "\n", " import random\n", "\n", " L = [i + 1 for i in range(N)]\n", " random.shuffle(L)\n", "\n", " for v in L:\n", " yield v" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "R = randomGenerator(5)\n", "for i in range(5):\n", " print(next(R))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(next(R))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def randomGenerator(N):\n", "\n", " import random\n", "\n", " while True:\n", "\n", " L = [i + 1 for i in range(N)]\n", " random.shuffle(L)\n", "\n", " for v in L:\n", " yield v" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "R = randomGenerator(5)\n", "for i in range(50):\n", " print(next(R))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "SyzbOn2dseNo" }, "outputs": [], "source": [ "def myRange(start=0, end=0, step=1):\n", " current = start\n", " while current < end:\n", " yield current\n", " current += step" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "R = myRange(0, 10, 2)\n", "for value in R:\n", " print(value)" ] }, { "cell_type": "markdown", "metadata": { "id": "fymwj8_RseNo" }, "source": [ "## 星號 args kargs" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def argsTest(*args):\n", " print(f'Parameter count: {len(args)}')\n", " print(args)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "argsTest(1, 3, 5)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def kargsTest(*args, **kargs):\n", " print(f'Parameter count: {len(args)}')\n", " print(args)\n", " print(f'Named Parameter count: {len(kargs)}')\n", " print(kargs)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "kargsTest(1, 2, 3, 4, 5, a='1', b=2, c=3)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "YcEnSFdEseNo" }, "outputs": [], "source": [ "def myRange(*args):\n", " start, end, step = 0, 0, 1\n", " if len(args) == 1:\n", " end = args[0]\n", " elif len(args) == 2:\n", " start, end = args[0], args[1]\n", " elif len(args) == 3:\n", " start, end, step = args[0], args[1], args[2]\n", " current = start\n", " while current < end:\n", " yield current\n", " current += step" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for value in myRange(10):\n", " print(value)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for value in myRange(2, 10):\n", " print(value)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for value in myRange(1, 10, 3):\n", " print(value)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 練習:輸入一個數字,找出小於該數字的所有質數\n", "def find_prime(x):\n", "\n", " prime = [True] * (x + 1)\n", " prime[0] = False\n", " prime[1] = False\n", "\n", " i = 2\n", " while i < x:\n", "\n", " while i < x and prime[i] == False:\n", " i += 1\n", "\n", " for value in range(2*i, x+1, i):\n", " prime[value] = False\n", "\n", " i += 1\n", "\n", " return [index for index, value in enumerate(prime) if value == True]\n", "\n", "\n", "print(find_prime(1))\n", "print(find_prime(2))\n", "print(find_prime(5))\n", "print(find_prime(7))\n", "print(find_prime(11))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "\n", "---\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Quiz" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "YZZP9ev2seNo" }, "outputs": [], "source": [ "# quiz1: 實作一個 lambda function,把輸入(數字)平方之後加上 5 回傳。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "v_dje-IKseNp" }, "outputs": [], "source": [ "# quiz2: 實作一個 function,輸入寬 (w) 及長 (l) 後印出如附圖所示的鉛筆形狀。\n", "\n", "# |******\n", "# |*******\n", "# w********\n", "# |*******\n", "# |******\n", "# --l--\n", "\n", "# e.g. \n", "# pencil(5, 6) 會印出\n", "# *******\n", "# ********\n", "# *********\n", "# ********\n", "# *******\n", "\n", "def pencil(w, l):\n", " pass" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "vjZxKfg-seNp" }, "outputs": [], "source": [ "# quiz3: 建構一個 費式數列 的 generator\n", "\n", "# 使用 next() 的時候\n", "# 第一次 yield 1\n", "# 第二次 yield 1\n", "# 第三次 yield 2\n", "# 第四次 yield 3\n", "# 第五次 yield 5\n", "# ... 以此類推\n", "\n", "def fib_generator():\n", " # your code here" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "jMtxUBvuseNp" }, "outputs": [], "source": [ "# 可以使用此段程式驗證你的 generator 有沒有成功\n", "\n", "f = fib_generator()\n", "for i in range(10):\n", " print(next(f))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "colab": { "name": "5 Functions.ipynb", "provenance": [] }, "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.7.6" }, "vscode": { "interpreter": { "hash": "f2c5ff1dcfb7037f8bc8783b5d7cd749bee6b69d77e75d46cb9007d97777ae49" } } }, "nbformat": 4, "nbformat_minor": 4 }