Skip to content

Instantly share code, notes, and snippets.

@phwt
Last active June 26, 2019 13:03
Show Gist options
  • Save phwt/4749e6cc67f26122db020742e3324d5c to your computer and use it in GitHub Desktop.
Save phwt/4749e6cc67f26122db020742e3324d5c to your computer and use it in GitHub Desktop.
Python-T1
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"metadata": {
"collapsed": true
},
"cell_type": "markdown",
"source": "# Code Refactoring and Shortening\n\n## คำสั่งที่ควรรู้\n\n## `lambda`\n\n**Syntax**\n\n`lambda arguments : expression`\n\n`lambda` คือ Function รูปแบบย่อ ซึ่งจะรับ Arguments กี่ตัวก็ได้แต่สามารถส่งค่าออกได้แค่หนึ่งอย่างเท่านั้น"
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "add = lambda a, b: a + b\nadd(3,4)",
"execution_count": 1,
"outputs": [
{
"data": {
"text/plain": "7"
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
]
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "def add(a, b):\n \"\"\" Plus two numbers \"\"\"\n return a + b\nadd(3,4)",
"execution_count": 3,
"outputs": [
{
"data": {
"text/plain": "7"
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "จะเห็นได้ว่าการใช้ `lambda` จะใช้บรรทัดน้อยลงไปถึง 2 บรรทัดแต่ยังคงให้ผลลัพธ์เท่าเดิม เนื่องจากไม่จำเป็นต้องเขียน docstring และสามารถ Return ค่าได้ในบรรทัดเดียวกัน\n\n---"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## `if else`\n\n**Syntax**\n\n`statement if condition else statement` / `statement if condition else statement if statement else...`\n\nในส่วนนี้จะกล่าวถึงการใช้ `if else` ในรูปแบบย่อ ซึ่งสามารถใช้แทน `if else` ในรูปแบบปกติได้ในเกือบทุกกรณี"
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "x = True\nif x:\n print(\"Yes!\")\nelse:\n print(\"Nah\")",
"execution_count": 16,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "Yes!\n"
}
]
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "x = True\nprint(\"Yes!\" if x else \"Nah\")",
"execution_count": 17,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "Yes!\n"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "จะเห็นได้ว่าโค้ดทั้งสองให้ผลลัพธ์เหมือนกันแต่การใช้แบบย่อจะเขียนได้อยู่ในบรรทัดเดียว โดยสามารถมีกรณีอื่นๆเหมือนการใช้ `elif` ได้ตามปกติเหมือนดังโค้ดด้านล่าง"
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "x = \"B\"\nprint(\"It's A\" if x == \"A\" else \"It's B\" if x == \"B\" else \"It's nor A or B\")",
"execution_count": 18,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "It's B\n"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "---"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## `for`\n\n`for` ในที่นี้ไม่ได้กล่าวถึงการลูปแบบปกติ แต่จะเป็นการลูปเพื่อรับค่า, สร้าง list ฯลฯ โดยจะแสดงให้ให้ทั้งการใช้ `for` แบบปกติและแบบอยู่ใน list"
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "x = []\nfor _ in range(0,3):\n x.append(input())\nprint(x)",
"execution_count": 12,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "1\n2\n3\n['1', '2', '3']\n"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "คำสั่งด้านบนเป็นการใช้ `for` เพื่อรับค่า 3 ค่ามาเพิ่มไปใน list `x` ซึ่งสามาถเขียนแบบสั้นๆโดยนำ `[]` มาครอบได้แบบด้านล่างนี้"
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "x = [input() for _ in range(0, 3)]\nprint(x)",
"execution_count": 13,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "Hello There!\nGeneral Kenobi!\nYou are a bold one.\n['Hello There!', 'General Kenobi!', 'You are a bold one.']\n"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "การใช้ `for` ใน list เลยจะทำให้โด้ดสั้นลงได้และยังได้ผลลัพธ์เหมือนเดิม"
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "x = [i for i in range(0, 5)]\nprint(x)",
"execution_count": 14,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "[0, 1, 2, 3, 4]\n"
}
]
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "x = [chr(i) for i in range(65, 91)]\nprint(x)",
"execution_count": 15,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']\n"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "และยังสามารถใช้เหมือนด้านบนเพื่อทำการสร้าง list ของค่าต่างๆได้\n\n---"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## `map()`\n\n**Syntax**\n\n`map(function, iterables)`\n\n`map()` เป็น Built-in Function ชนิดหนึ่งที่ใช้ในการรัน Function ลงไปใน iterables หรือ Object ที่บรรจุค่าได้เช่น list และ tuple\n\n**หมายเหตุ** - การจะแสดงผล map จำเป็นต้องแปลงให้เป็น list ก่อนโดยการครอบ `list()` ไว้ (ตัวอย่าง: `list(map(int, [\"1\", \"2\", \"3\"]))`)"
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "def first(n):\n return n[0]\nlist(map(first, [\"India\", \"Alpha\", \"Mike\", \"Tango\", \"Hotel\", \"Echo\", \"Sierra\", \"Echo\", \"November\", \"Alpha\", \"Tango\", \"Echo\"]))",
"execution_count": 5,
"outputs": [
{
"data": {
"text/plain": "['I', 'A', 'M', 'T', 'H', 'E', 'S', 'E', 'N', 'A', 'T', 'E']"
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "Function `first()` นั้นใช้เพื่อแปลง String ให้เหลือแค่ตัวอักษรตัวแรก ซึ่งเราก็สามารถใช้ `map()` ในการช่วงแปลง String ที่อยู่ใน list ให้เหลือต่ตัวแรกด้วย Function `first()` ของเราได้"
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "x = [input(), input(), input()]\nlist(map(int, x))",
"execution_count": 9,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "44\n122\n120\n"
},
{
"data": {
"text/plain": "[44, 122, 120]"
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "จากโค้ดด้านบน list `x` เป็นการ input เข้ามา 3 ตัว ซึ่งค่า Default ของการ Input คือ String หากเราจะรับเป็น Int หรืออื่นๆก็จะต้องรับเป็น `int(input())` ซึ่งหากมี Input เป็นจำนวนมากและไม่สามารถใช้ `for` ได้การใช้ map แปลงค่าจะทำให้สั้นกว่า\n\n---"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## `join()`\n\n**Syntax**\n\n`string.join(iterable)`\n\n`join()` เป็น Built-in Function ที่ใช้ในการรวม iterable เข้าด้วยกัน โดย string ด้านหน้าจะเป็นตัวกำหนดตัวที่ใช้เชื่อม"
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "\" \".join([\"Not\", \"yet\"])",
"execution_count": 19,
"outputs": [
{
"data": {
"text/plain": "'Not yet'"
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
]
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "\"+\".join([\"1\",\"2\",\"3\"])",
"execution_count": 20,
"outputs": [
{
"data": {
"text/plain": "'1+2+3'"
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "---"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## `import`\n\n**Syntax**\n\n`from library import module`\n\nการ import ด้วยรูปแบบนี้จะทำให้ไม่ต้อง import ทุกตัวของ Library นั้นมาและการเขียนจะสั้นลง"
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "import math\nmath.pi",
"execution_count": 25,
"outputs": [
{
"data": {
"text/plain": "3.141592653589793"
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
]
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "from math import pi\npi",
"execution_count": 27,
"outputs": [
{
"data": {
"text/plain": "3.141592653589793"
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "จากตัวอย่างด้านบนหากเรามีการเรียกใช้งาน `pi` มากๆ แทนที่จะเขียนว่า `math.pi` จะเขียนแค่ `pi` ซึ่งจะทำให้โค้ดโดยรวมนั้นสั้นลง\nซึ่งการ import แบบนี้สามารถเลือกใช้หลายตัวได้ตามตัวอย่างด้านล่าง"
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "from math import pi, sqrt\npi,sqrt(2)",
"execution_count": 29,
"outputs": [
{
"data": {
"text/plain": "(3.141592653589793, 1.4142135623730951)"
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "---"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## การใช้ `print()` ให้สั้น\n\nหากค่ามีไม่มากให้รับค่าใน print เลย"
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "print(\"Result: \" + str(int(input()) + int(input())))",
"execution_count": 35,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "4\n5\nResult: 9\n"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "---\nใช้ `\\n` ในการ print หลายบรรทัด แทนการใช้ print หลายบรรทัดแทน โดยจะใช้ร่วมกัน `sep` ในรูปแบบ `sep=\"\\n\"` ก็ได้"
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "print(\"A\\nB\\nC\")",
"execution_count": 37,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "A\nB\nC\n"
}
]
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "print(1, 2, 3, sep=\"\\n\")",
"execution_count": 30,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "1\n2\n3\n"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "---\nใช้ `if else` ภายใน print"
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "x = 1\nprint(\"Yes, it is\" if x else \"No, it isn't\")",
"execution_count": 36,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "Yes, it is\n"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "---"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## การนำ `lambda` `map()` และ `list()` มารวมกันเพื่อ `print()` ในบรรทัดเดียว\n\n**Syntax**\n\n`print(*list(map((lambda args: return), [value])))`\n\nตามรูปแบบดังกล่าวเราสามารถรับค่า > เข้าสูตร > print แสดงค่าได้ในบรรทัดเดียว\n\n---\n**หมายเหตุ** - หากมีการจำกัดห้ามใช้ `list()` หรือ `[]` ให้ใช้ Syntax ตามนี้แทน `print(*tuple(map((lambda args: return), (value, ))))`\n\n---\n\n**ตัวอย่าง 1:**\n\nโดยด้านล่างจะเป็นโค้ดสำหรับรับคะแนนและบอกว่าผ่านหรือไม่ โดยจะผ่านเมื่อมากกว่า 60\n\nจะเขียนเป็น 3 รูปแบบคือแบบปกติ, แบบการใช้ `lambda` ช่วย และแบบการใช้ `lambda` `map()` และ `list()` ร่วมกัน ตามลำดับ"
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "def grade(x):\n \"\"\" Check your grade \"\"\"\n if x >= 60:\n return \"Pass\"\n else:\n return \"Fail\"\n #ใช้เป็น return \"Pass\" if float(x) >= 60 else \"Fail\" ก็ได้\nprint(grade(float(input())))",
"execution_count": 42,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "75\nPass\n"
}
]
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "grade = lambda x: \"Pass\" if float(x) >= 60 else \"Fail\"\nprint(grade(input()))",
"execution_count": 39,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "75\nPass\n"
}
]
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "print(*list(map((lambda x: \"Pass\" if float(x) >= 60 else \"Fail\"), [input()])))",
"execution_count": 38,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "75\nPass\n"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "แต่นี้เป็นแค่ตัวอย่างเฉยๆ สำหรับโจทย์นี้หากจะให้สั้นที่สุดไม่จำเป็นต้องใช้ `lambda` ก็ได้"
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "print(\"Pass\" if float(input()) >= 60 else \"Fail\")",
"execution_count": 1,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "75\nPass\n"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "---\n**ตัวอย่าง 2:**\n\nโค้ดด้านล่างจะเป็นการรับคำมาสองคำและนำมาต่อกัน จากนั้นให้รับจำนวนเต็มมาเพื่อกำหนดว่าแสดงผลคำนั้นๆกี่รอบ โดยจะแสดงเป็น 3 รูปแบบเหมือนในตัวอย่าง 1"
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "def repeat(i, j):\n \"\"\" Repeat i word j time(s)\"\"\"\n return (i + \"\\n\") * j\nprint(repeat((input() + input()), int(input())))",
"execution_count": 48,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "Right Full Rudder!\nReverse Starboard Engine!\n3\nRight Full Rudder!Reverse Starboard Engine!\nRight Full Rudder!Reverse Starboard Engine!\nRight Full Rudder!Reverse Starboard Engine!\n\n"
}
]
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "repeat = lambda i, j: (i + \"\\n\") * j\nprint(repeat((input() + input()), int(input())))",
"execution_count": 47,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "Right Full Rudder!\nReverse Starboard Engine!\n3\nRight Full Rudder!Reverse Starboard Engine!\nRight Full Rudder!Reverse Starboard Engine!\nRight Full Rudder!Reverse Starboard Engine!\n\n"
}
]
},
{
"metadata": {
"scrolled": true,
"trusted": false
},
"cell_type": "code",
"source": "print(*list(map((lambda i, j: (i + \"\\n\") * j), [input() + input()], [int(input())])))",
"execution_count": 44,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "Right Full Rudder!\nReverse Starboard Engine!\n3\nRight Full Rudder!Reverse Starboard Engine!\nRight Full Rudder!Reverse Starboard Engine!\nRight Full Rudder!Reverse Starboard Engine!\n\n"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "3 แบบด้านนี้ก็เป็นตัวอย่างเช่นเคย ซึ่งด้านบนก็สามารถเขียนให้สั้นกว่าโดยใช้แบบด้านล่างนี้ก็ได้"
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "print((input() + input() + \"\\n\") * int(input()))",
"execution_count": 1,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "Right Full Rudder!\nReverse Starboard Engine!\n3\nRight Full Rudder!Reverse Starboard Engine!\nRight Full Rudder!Reverse Starboard Engine!\nRight Full Rudder!Reverse Starboard Engine!\n\n"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "---\n**ตัวอย่าง 3:**\n\nโด้ดในข้อนี้จะเป็นการรับจำนวนเต็มมา 5 ค่า และให้แสดงค่าที่เป็นจำนวนคี่ซึ่งจะมีแค่จำนวนเดียวจาก 5 จำนวน"
},
{
"metadata": {
"trusted": false
},
"cell_type": "code",
"source": "print(\"Odd is: \" + str(sum(list(map(lambda a: a if a%2 else 0, list(map(int, ([input(), input(), input(), input(), input()]))))))))",
"execution_count": 4,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "12\n30\n8\n67\n102\nOdd is: 67\n"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "โค้ดด้านบนนั้นทำงานอย่างไร ให้ดูใน Arguments ที่สองของ map กันก่อน (มีการตัด `\"Odd is: \" + str()` ออก)\n\n`print(sum(list(map(lambda a: a if a%2 else 0,`**`list(map(int, ([input(), input(), input(), input(), input()])))`**`))))`\n\nตรงนี้คือส่วนที่เรารับค่าทั้ง 5 ตัวเข้ามา(โดยไม่ใช้ `for`) ซึ่งรับมาเป็น `string` เลยนำ `map(int, iter)` มาครอบเพื่อแปลงค่าข้างในให้เป็น `int` ให้หมด และครอบด้วย `list()` อีกที่เพื่อให้ map object กลายเป็น list\n\nส่วนต่อไปคือ lambdaซึ่งเป็น Arguments ตัวแรกของ map\n\n`print(sum(list(map(`**`lambda a: a if a%2 else 0`**`, list(map(int, ([input(), input(), input(), input(), input()])))))))`\n\nการใช้ `map()` จะเป็นการนำ function เข้าไปรันกับค่าภายใน list ทีละตัว ซึ่ง `lambda` ก็คือ function ชนิดหนึ่ง โดย lambda ด้านบนของเรานั้นจะเป็นการรับค่า `a` เข้ามา ซึ่งก็คือค่าต่างๆใน list และใส่ `if else` ว่า **\"ให้คืนค่าเป็น a ถ้า a%2 = 1 หากเป็นแบบอื่นๆให้คืนค่าเป็น 0\"** ดังนั้นค่าที่เข้ามาหากค่านั้นเป็นจำนวนคู่ค่านั้นก็จะกลายเป็น 0 แต่ถ้าเป็นคี่ค่าก็จะไม่เปลี่ยน\n\nทำให้จากที่เรา input ไปด้านบนคือ `[12, 30, 8, 67, 102]` จะกลายเป็น `[0, 0, 0, 67, 0]`\n\nจากนั้นครอบ `map()` ด้วย `list()` เพื่อให้กลายเป็น list จากนั้น `sum()` เพื่อรวมค่าใน list เข้าด้วยกันและ `print()` ค่านั้นออกมาโดยค่านั้นก็คือ `67`"
}
],
"metadata": {
"kernelspec": {
"name": "python36",
"display_name": "Python 3.6",
"language": "python"
},
"language_info": {
"mimetype": "text/x-python",
"nbconvert_exporter": "python",
"name": "python",
"pygments_lexer": "ipython3",
"version": "3.6.6",
"file_extension": ".py",
"codemirror_mode": {
"version": 3,
"name": "ipython"
}
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment