{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.1 개요"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.2 22가지 프로그래밍 지름길"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4.2.1 필요하다면 코드를 여러 줄에 걸쳐서 작성한다"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"I am Hen-er-y the Eighth, I am!\n"
]
}
],
"source": [
"my_str = 'I am Hen-er-y the Eighth,' ' I am!'\n",
"print(my_str)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'I am Hen-er-y the Eighth, I am!'"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_str = 'I am Hen-er-y the Eighth,' \\\n",
"' I am!'\n",
"my_str"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'I am Hen-er-y the Eighth, I am! I am not just any Henry VIII, I really am!'"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_str = ('I am Hen-er-y the Eighth, '\n",
"'I am! I am not just any Henry VIII, '\n",
"'I really am!')\n",
"my_str"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [
{
"data": {
"text/plain": [
"tuple"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a = 10, 5\n",
"type(a)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"side1, side2 = a"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [
{
"data": {
"text/plain": [
"10"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"side1"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"side2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"11.180339887498949"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"side1, side2 = 10, 5\n",
"length_of_hypotenuse = ( (side1 * side1 + side2 * side2)\n",
" ** 0.5 )\n",
"length_of_hypotenuse"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [
{
"data": {
"text/plain": [
"11.180339887498949"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"side1, side2 = 10, 5\n",
"length_of_hypotenuse = (side1 * side1 + side2 * side2) \\\n",
" ** 0.5\n",
"length_of_hypotenuse"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4.2.2\t for 루프는 현명하게 사용한다."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"John\n",
"Paul\n",
"George\n",
"Ringo\n"
]
}
],
"source": [
"beat_list = ['John', 'Paul', 'George', 'Ringo']\n",
"for i in range(len(beat_list)):\n",
" print(beat_list[i])"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"John\n",
"Paul\n",
"George\n",
"Ringo\n"
]
}
],
"source": [
"beat_list = ['John', 'Paul', 'George', 'Ringo']\n",
"for guy in beat_list:\n",
" print(guy)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1. John\n",
"2. Paul\n",
"3. George\n",
"4. Ringo\n"
]
}
],
"source": [
"beat_list = ['John', 'Paul', 'George', 'Ringo']\n",
"for i, name in enumerate(beat_list, 1):\n",
" print(i, '. ', name, sep='')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4.2.3 조합 대입 연산자를 이해한다. (예: +=)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![](./images_skill_up/4-2.PNG)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"s1: A string....with more stuff!\n",
"s2: A string.\n"
]
}
],
"source": [
"s1 = s2 = 'A string.'\n",
"s1 += '...with more stuff!'\n",
"print('s1:', s1)\n",
"print('s2:', s2)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a_list: [10, 20, 30, 40]\n",
"b_list: [10, 20, 30, 40]\n"
]
}
],
"source": [
"a_list = b_list = [10, 20]\n",
"a_list += [30, 40]\n",
"print('a_list:', a_list)\n",
"print('b_list:', b_list)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'abcdefghijklmnopqrstuvwxyz'"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"str_list = []\n",
"n = ord('a')\n",
"for i in range(n, n + 26):\n",
" str_list += chr(i)\n",
"alphabet_str = ''.join(str_list)\n",
"alphabet_str"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4.2.4 다중 대입을 사용한다"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"a = b = c = d = e = 0"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a is b"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4.2.5 튜플 대입을 사용한다"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"a = 1\n",
"b = 0"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"a, b = 1, 0"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(4, 8, 12)"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a = 4, 8, 12 \t\t# a는 이제 3개 값을 지닌 튜플이다.\n",
"a"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"30 10\n"
]
}
],
"source": [
"a, b = 10, 20\n",
"temp = a \t# a 기존 값 보존\n",
"a = a + b \t# a에 신규 값 설정\n",
"b = temp \t# b에 a 기존 값 저장 \n",
"print(a, b)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"30 10\n"
]
}
],
"source": [
"a, b = 10, 20\n",
"a, b = a + b, a\n",
"print(a, b)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1 1 2 3 5 8 "
]
}
],
"source": [
"def fibo(n):\n",
" a, b = 1, 0\n",
"\n",
" while a <= n:\n",
" print(a, end=' ')\n",
" a, b = a + b, a\n",
"\n",
"fibo(10)"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1 25\n",
"25 1\n"
]
}
],
"source": [
"x, y = 1, 25\n",
"print(x, y) \t# 1 25 출력\n",
"x, y = y, x\n",
"print(x, y) \t# 25 1 출력"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"a, b, c = [1, 2, 3]"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1 2 3\n"
]
}
],
"source": [
"print(a, b, c)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4.2.6 고급 튜플 대입을 사용한다"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"10 20 30\n"
]
}
],
"source": [
"tup = 10, 20, 30 # 패킹 (Packing)\n",
"a, b, c = tup # 언패킹 (Unpacking)\n",
"print(a, b, c) \t\t# 10, 20, 30 출력"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"ename": "ValueError",
"evalue": "too many values to unpack (expected 2)",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mValueError\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 1\u001b[0m \u001b[0mtup\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m10\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m20\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m30\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0ma\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mb\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mtup\u001b[0m \u001b[0;31m# 에러: 언팩 대상 값이 너무 많음\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mValueError\u001b[0m: too many values to unpack (expected 2)"
]
}
],
"source": [
"tup = 10, 20, 30\n",
"a, b = tup \t\t# 에러: 언팩 대상 값이 너무 많음"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"my_list = [3]"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n"
]
}
],
"source": [
"my_tup = (3)\n",
"print(type(my_tup))"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n"
]
}
],
"source": [
"my_tup = (3,) \t# 한 항목 3을 가진 튜플 만들기\n",
"print(type(my_tup))"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2 [4, 6, 8]\n"
]
}
],
"source": [
"a, *b = 2, 4, 6, 8\n",
"print(a, b)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"10 [20, 30, 40] 50\n"
]
}
],
"source": [
"a, *b, c = 10, 20, 30, 40, 50\n",
"print(a, b, c)"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [],
"source": [
"big, bigger, *many = 100, 200, 300, 400, 500, 600"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"100\n",
"200\n",
"[300, 400, 500, 600]\n"
]
}
],
"source": [
"print(big, bigger, many, sep='\\n')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4.2.7 리스트와 문자열 '곱하기'를 사용한다"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"10000"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_list = [0] * 10000\n",
"len(my_list)"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1999"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_list = 1999 * [12]\n",
"len(my_list)"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"300"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"trip_list = [1, 2, 3] * 100\n",
"len(trip_list)"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'________________________________________'"
]
},
"execution_count": 34,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"divider_str = '_' * 40\n",
"divider_str"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4.2.8 다중 값을 반환한다"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"10\n"
]
}
],
"source": [
"def double_me(n):\n",
" n *= 2\n",
"\n",
"a = 10\n",
"double_me(a)\n",
"print(a) \t# a 값이 두배가 되지 않는다!!"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"20\n"
]
}
],
"source": [
"def double_me(n):\n",
" return n * 2\n",
"\n",
"a = 10\n",
"a = double_me(a)\n",
"print(a)"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [],
"source": [
"def quad(a, b, c):\n",
" determin = (b * b - 4 * a * c) ** .5\n",
" x1 = (-b + determin) / (2 * a)\n",
" x2 = (-b - determin) / (2 * a)\n",
" return x1, x2"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [],
"source": [
"x1, x2 = quad(1, -1, -1)"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(1.618033988749895, -0.6180339887498949)"
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x = quad(1, -1, -1)\n",
"x"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4.2.9 루프와 else 키워드를 사용한다"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [],
"source": [
"def find_divisor(n, max):\n",
" for i in range(2, max + 1):\n",
" if n % i == 0:\n",
" print(i, 'divides evenly into', n)\n",
" break\n",
" else: # break를 만나서 일찍 빠져나오지 않는 한 루프 종료시 수행된다.\n",
" print('No divisor found')"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"No divisor found\n"
]
}
],
"source": [
"find_divisor(49, 6)"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"7 divides evenly into 49\n"
]
}
],
"source": [
"find_divisor(49, 7)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4.2.10\t 불리언과 'not'의 이점을 활용한다"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [],
"source": [
"my_str = ''\n",
"while True:\n",
" if len(my_str) == 0:\n",
" break"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [],
"source": [
"while True:\n",
" if not my_str:\n",
" break"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4.2.11\t 문자열은 문자의 나열로 다룬다"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['A', 'B', 'C', 'B', 'A']\n",
"True\n"
]
}
],
"source": [
"test_str = input('Enter test string: ')\n",
"a_list = [c.upper() for c in test_str if c.isalnum()]\n",
"print(a_list)\n",
"print(a_list == a_list[::-1])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4.2.12\t replace를 사용하여 문자를 제거한다"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'1/2'"
]
},
"execution_count": 46,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s = '1 / 2'\n",
"s = s.replace(' ', '')\n",
"s"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'sm dy'"
]
},
"execution_count": 47,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s = 'same day'\n",
"a_list = [c for c in s if c not in 'aeiou']\n",
"s = ''.join(a_list)\n",
"s"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [
{
"data": {
"text/plain": [
"'sm dy'"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s = 'same day'\n",
"s = s.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')\n",
"s"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4.2.13\t 필요 없는 루프는 사용하지 않는다"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [
{
"data": {
"text/plain": [
"55"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def calc_triangle_num(n):\n",
" s = 0\n",
" for i in range(n + 1):\n",
" s += i\n",
" return s\n",
"\n",
"calc_triangle_num(10)"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"55"
]
},
"execution_count": 48,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def calc_triangle_num(n):\n",
" return sum(range(n + 1))\n",
"\n",
"calc_triangle_num(10)"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [
{
"data": {
"text/plain": [
"25.0"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def get_avg(a_list):\n",
" s = 0\n",
" for i in a_list:\n",
" s += i\n",
"\n",
" return s / len(a_list)\n",
"\n",
"get_avg([10, 20, 30, 40])"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"25.0"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def get_avg(a_list):\n",
" return sum(a_list) / len(a_list)\n",
"\n",
"get_avg([10, 20, 30, 40])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4.2.14\t 연결된(chained) 비교 연산자를 사용한다"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x is in range.\n"
]
}
],
"source": [
"x = 55\n",
"if 0 < x and x < 100:\n",
" print('x is in range.')"
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x is in range.\n"
]
}
],
"source": [
"if 0 < x < 100: \t\t\t# 연결된(chained) 비교 연산자 사용\n",
" print('x is in range.')"
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"All these comparisons are true!\n",
"c is equal or greater than all the rest!\n"
]
}
],
"source": [
"a, b, c = 5, 10, 15\n",
"if 0 < a <= c > b > 1:\n",
" print('All these comparisons are true!')\n",
" print('c is equal or greater than all the rest!')"
]
},
{
"cell_type": "code",
"execution_count": 53,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"All the variables are equal to each other.\n"
]
}
],
"source": [
"a = b = c = d = e = 100\n",
"if a == b == c == d == e:\n",
" print('All the variables are equal to each other.')"
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"All the elements are equal to each other.\n"
]
}
],
"source": [
"a_list = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ,1 ,1]\n",
"if min(a_list) == max(a_list):\n",
" print('All the elements are equal to each other.')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4.2.15\t 함수 테이블(리스트, 딕셔너리)로 'switch'를 모방한다"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"hello, insuk\n"
]
}
],
"source": [
"n = 1\n",
"\n",
"def test(name='init'):\n",
" print('hello,', name)\n",
"\n",
"do_plot = do_highlow_plot = do_volume_subplot = do_movingavg_plot = test\n",
"\n",
"stockdf = 'insuk'\n",
"\n",
"if n == 1:\n",
" do_plot(stockdf)\n",
"elif n == 2:\n",
" do_highlow_plot(stockdf)\n",
"elif n == 3:\n",
" do_volume_subplot(stockdf)\n",
"elif n == 4:\n",
" do_movingavg_plot(stockdf)"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"hello, insuk\n"
]
}
],
"source": [
"n = 1\n",
"fn = [do_plot, do_highlow_plot, do_volume_subplot, do_movingavg_plot][n - 1]\n",
"fn(stockdf) \t\t# 함수 호출"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"hello, insuk\n"
]
}
],
"source": [
"n = 1\n",
"f_list = [do_plot, do_highlow_plot, do_volume_subplot, do_movingavg_plot]\n",
"fn = f_list[n - 1]\n",
"fn(stockdf) \t\t# 함수 호출"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"hello, init\n"
]
}
],
"source": [
"load_fn = save_fn = exit_fn = update_fn = test\n",
"menu_dict = {'load':load_fn, 'save':save_fn, 'exit':exit_fn, 'update':update_fn}\n",
"\n",
"selector = 'exit'\n",
"(menu_dict[selector])() \t\t\t# 함수 호출"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4.2.16\t is 연산자는 정확하게 사용한다"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a = 'cat'\n",
"b = 'cat'\n",
"a == b \t\t# 반드시 True 반환"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s1 = 'I am what I am and that is all that I am.'\n",
"s2 = 'I am what I am' + ' and that is all that I am.'\n",
"s1 == s2"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s1 is s2"
]
},
{
"cell_type": "code",
"execution_count": 61,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a_value 함수의 반환값은 None이다.\n"
]
}
],
"source": [
"def my_function():\n",
" return None\n",
"\n",
"a_value = my_function()\n",
"\n",
"if a_value is None: # 이곳에 if a_value == None 은 불가!!!\n",
" # None이 반환되면 특별한 행동을 취해라.\n",
" print('a_value 함수의 반환값은 None이다.')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4.2.17\t 단일 행 for 루프를 사용한다"
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0 1 2 3 4 5 6 7 8 9 "
]
}
],
"source": [
"for i in range(10): print(i, end=' ')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4.2.18\t 여러 문장을 하나의 행으로 줄인다"
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5 7 9 11 13 "
]
}
],
"source": [
"for i in range(5): n=i*2; m = 5; print(n+m, end=' ')"
]
},
{
"cell_type": "code",
"execution_count": 64,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3\n"
]
}
],
"source": [
"a = 1; b = 2; c = a + b; print(c)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4.2.19\t 단일 행 if/then/else 문을 작성한다"
]
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'O'"
]
},
"execution_count": 65,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"turn = 0\n",
"\n",
"if turn % 2:\n",
" cell = 'X'\n",
"else:\n",
" cell = 'O'\n",
"\n",
"cell"
]
},
{
"cell_type": "code",
"execution_count": 66,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'O'"
]
},
"execution_count": 66,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"cell = 'X' if turn % 2 else 'O'\n",
"cell"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4.2.20\t range와 함께 Enum을 생성한다"
]
},
{
"cell_type": "code",
"execution_count": 67,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0 1 2 3 4\n"
]
}
],
"source": [
"red = 0\n",
"blue = 1\n",
"green = 2\n",
"black = 3\n",
"white = 4\n",
"\n",
"print(red, blue, green, black, white)"
]
},
{
"cell_type": "code",
"execution_count": 68,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0 1 2 3 4\n"
]
}
],
"source": [
"red, blue, green, black, white = range(5)\n",
"print(red, blue, green, black, white)"
]
},
{
"cell_type": "code",
"execution_count": 69,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1 2 3 4 5\n"
]
}
],
"source": [
"red, blue, green, black, white = range(1, 6)\n",
"print(red, blue, green, black, white)"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Help on module enum:\n",
"\n",
"NAME\n",
" enum\n",
"\n",
"MODULE REFERENCE\n",
" https://docs.python.org/3.9/library/enum\n",
" \n",
" The following documentation is automatically generated from the Python\n",
" source files. It may be incomplete, incorrect or include features that\n",
" are considered implementation detail and may vary between Python\n",
" implementations. When in doubt, consult the module reference at the\n",
" location listed above.\n",
"\n",
"CLASSES\n",
" builtins.int(builtins.object)\n",
" IntEnum(builtins.int, Enum)\n",
" IntFlag(builtins.int, Flag)\n",
" builtins.object\n",
" Enum\n",
" Flag\n",
" IntFlag(builtins.int, Flag)\n",
" IntEnum(builtins.int, Enum)\n",
" auto\n",
" builtins.type(builtins.object)\n",
" EnumMeta\n",
" \n",
" class Enum(builtins.object)\n",
" | Enum(value, names=None, *, module=None, qualname=None, type=None, start=1)\n",
" | \n",
" | Generic enumeration.\n",
" | \n",
" | Derive from this class to define new enumerations.\n",
" | \n",
" | Data descriptors defined here:\n",
" | \n",
" | name\n",
" | The name of the Enum member.\n",
" | \n",
" | value\n",
" | The value of the Enum member.\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Readonly properties inherited from EnumMeta:\n",
" | \n",
" | __members__\n",
" | Returns a mapping of member name->value.\n",
" | \n",
" | This mapping lists all enum members, including aliases. Note that this\n",
" | is a read-only view of the internal mapping.\n",
" \n",
" class EnumMeta(builtins.type)\n",
" | EnumMeta(cls, bases, classdict)\n",
" | \n",
" | Metaclass for Enum\n",
" | \n",
" | Method resolution order:\n",
" | EnumMeta\n",
" | builtins.type\n",
" | builtins.object\n",
" | \n",
" | Methods defined here:\n",
" | \n",
" | __bool__(self)\n",
" | classes/types should always be True.\n",
" | \n",
" | __call__(cls, value, names=None, *, module=None, qualname=None, type=None, start=1)\n",
" | Either returns an existing member, or creates a new enum class.\n",
" | \n",
" | This method is used both when an enum class is given a value to match\n",
" | to an enumeration member (i.e. Color(3)) and for the functional API\n",
" | (i.e. Color = Enum('Color', names='RED GREEN BLUE')).\n",
" | \n",
" | When used for the functional API:\n",
" | \n",
" | `value` will be the name of the new class.\n",
" | \n",
" | `names` should be either a string of white-space/comma delimited names\n",
" | (values will start at `start`), or an iterator/mapping of name, value pairs.\n",
" | \n",
" | `module` should be set to the module this class is being created in;\n",
" | if it is not set, an attempt to find that module will be made, but if\n",
" | it fails the class will not be picklable.\n",
" | \n",
" | `qualname` should be set to the actual location this class can be found\n",
" | at in its module; by default it is set to the global scope. If this is\n",
" | not correct, unpickling will fail in some circumstances.\n",
" | \n",
" | `type`, if set, will be mixed in as the first base class.\n",
" | \n",
" | __contains__(cls, member)\n",
" | \n",
" | __delattr__(cls, attr)\n",
" | Implement delattr(self, name).\n",
" | \n",
" | __dir__(self)\n",
" | Specialized __dir__ implementation for types.\n",
" | \n",
" | __getattr__(cls, name)\n",
" | Return the enum member matching `name`\n",
" | \n",
" | We use __getattr__ instead of descriptors or inserting into the enum\n",
" | class' __dict__ in order to support `name` and `value` being both\n",
" | properties for enum members (which live in the class' __dict__) and\n",
" | enum members themselves.\n",
" | \n",
" | __getitem__(cls, name)\n",
" | \n",
" | __iter__(cls)\n",
" | \n",
" | __len__(cls)\n",
" | \n",
" | __repr__(cls)\n",
" | Return repr(self).\n",
" | \n",
" | __reversed__(cls)\n",
" | \n",
" | __setattr__(cls, name, value)\n",
" | Block attempts to reassign Enum members.\n",
" | \n",
" | A simple assignment to the class namespace only changes one of the\n",
" | several possible ways to get an Enum member from the Enum class,\n",
" | resulting in an inconsistent Enumeration.\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Class methods defined here:\n",
" | \n",
" | __prepare__(cls, bases) from builtins.type\n",
" | __prepare__() -> dict\n",
" | used to create the namespace for the class statement\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Static methods defined here:\n",
" | \n",
" | __new__(metacls, cls, bases, classdict)\n",
" | Create and return a new object. See help(type) for accurate signature.\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Readonly properties defined here:\n",
" | \n",
" | __members__\n",
" | Returns a mapping of member name->value.\n",
" | \n",
" | This mapping lists all enum members, including aliases. Note that this\n",
" | is a read-only view of the internal mapping.\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Methods inherited from builtins.type:\n",
" | \n",
" | __getattribute__(self, name, /)\n",
" | Return getattr(self, name).\n",
" | \n",
" | __init__(self, /, *args, **kwargs)\n",
" | Initialize self. See help(type(self)) for accurate signature.\n",
" | \n",
" | __instancecheck__(self, instance, /)\n",
" | Check if an object is an instance.\n",
" | \n",
" | __sizeof__(self, /)\n",
" | Return memory consumption of the type object.\n",
" | \n",
" | __subclasscheck__(self, subclass, /)\n",
" | Check if a class is a subclass.\n",
" | \n",
" | __subclasses__(self, /)\n",
" | Return a list of immediate subclasses.\n",
" | \n",
" | mro(self, /)\n",
" | Return a type's method resolution order.\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Data descriptors inherited from builtins.type:\n",
" | \n",
" | __abstractmethods__\n",
" | \n",
" | __dict__\n",
" | \n",
" | __text_signature__\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Data and other attributes inherited from builtins.type:\n",
" | \n",
" | __base__ = \n",
" | type(object_or_name, bases, dict)\n",
" | type(object) -> the object's type\n",
" | type(name, bases, dict) -> a new type\n",
" | \n",
" | \n",
" | __bases__ = (,)\n",
" | \n",
" | __basicsize__ = 880\n",
" | \n",
" | __dictoffset__ = 264\n",
" | \n",
" | __flags__ = 2148292096\n",
" | \n",
" | __itemsize__ = 40\n",
" | \n",
" | __mro__ = (, , )\n",
" | \n",
" | __weakrefoffset__ = 368\n",
" \n",
" class Flag(Enum)\n",
" | Flag(value, names=None, *, module=None, qualname=None, type=None, start=1)\n",
" | \n",
" | Support for flags\n",
" | \n",
" | Method resolution order:\n",
" | Flag\n",
" | Enum\n",
" | builtins.object\n",
" | \n",
" | Data descriptors inherited from Enum:\n",
" | \n",
" | name\n",
" | The name of the Enum member.\n",
" | \n",
" | value\n",
" | The value of the Enum member.\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Readonly properties inherited from EnumMeta:\n",
" | \n",
" | __members__\n",
" | Returns a mapping of member name->value.\n",
" | \n",
" | This mapping lists all enum members, including aliases. Note that this\n",
" | is a read-only view of the internal mapping.\n",
" \n",
" class IntEnum(builtins.int, Enum)\n",
" | IntEnum(value, names=None, *, module=None, qualname=None, type=None, start=1)\n",
" | \n",
" | Enum where members are also (and must be) ints\n",
" | \n",
" | Method resolution order:\n",
" | IntEnum\n",
" | builtins.int\n",
" | Enum\n",
" | builtins.object\n",
" | \n",
" | Data descriptors inherited from Enum:\n",
" | \n",
" | name\n",
" | The name of the Enum member.\n",
" | \n",
" | value\n",
" | The value of the Enum member.\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Readonly properties inherited from EnumMeta:\n",
" | \n",
" | __members__\n",
" | Returns a mapping of member name->value.\n",
" | \n",
" | This mapping lists all enum members, including aliases. Note that this\n",
" | is a read-only view of the internal mapping.\n",
" \n",
" class IntFlag(builtins.int, Flag)\n",
" | IntFlag(value, names=None, *, module=None, qualname=None, type=None, start=1)\n",
" | \n",
" | Support for integer-based Flags\n",
" | \n",
" | Method resolution order:\n",
" | IntFlag\n",
" | builtins.int\n",
" | Flag\n",
" | Enum\n",
" | builtins.object\n",
" | \n",
" | Data descriptors inherited from Enum:\n",
" | \n",
" | name\n",
" | The name of the Enum member.\n",
" | \n",
" | value\n",
" | The value of the Enum member.\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Readonly properties inherited from EnumMeta:\n",
" | \n",
" | __members__\n",
" | Returns a mapping of member name->value.\n",
" | \n",
" | This mapping lists all enum members, including aliases. Note that this\n",
" | is a read-only view of the internal mapping.\n",
" \n",
" class auto(builtins.object)\n",
" | Instances are replaced with an appropriate value in Enum class suites.\n",
" | \n",
" | Data descriptors defined here:\n",
" | \n",
" | __dict__\n",
" | dictionary for instance variables (if defined)\n",
" | \n",
" | __weakref__\n",
" | list of weak references to the object (if defined)\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Data and other attributes defined here:\n",
" | \n",
" | value =