{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 수업 보충 자료" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 12. E-learning 22, 23 보충 자료" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 보충 내용 없음" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 11. E-learning 21 보충 자료" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1) Python 에서 Java에서 문법적으로 제공되는 것과 비슷하게 abstract class를 생성할 수 있나?\n", "- Python 문법 자체적으로 abstract class 지원하지 않음\n", "- abc 모듈을 활용하여 abstract class 생성할 수 있음 (참고적으로만 알아둘 것)\n", " - http://zaiste.net/2013/01/abstract_classes_in_python/" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "2) Python 에서 Java에서 문법적으로 제공되는 것과 비슷하게 interface를 생성할 수 있나?\n", "- Python 문법 자체적으로 interface 지원하지 않음\n", "- interface를 지원하는 모듈도 존재하지 않음" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 10. E-learning 19, 20 보충 자료" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 보충 내용 없음" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 9. E-learning 17, 18 보충 자료" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1) 특정 객체 내부에 지니고 있는 이름 알아보기 \n", "- dir(객체)\n", " : 이름 리스트 리스트 반환\n", "- 객체.\\_\\_dict\\_\\_\n", " : 이름 및 해당 이름에 할당된 객체의 repr (또는 str) 형태를 사전으로 지님" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Formatter', 'Template', '_TemplateMetaclass', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_float', '_idmap', '_idmapL', '_int', '_long', '_multimap', '_re', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'atof', 'atof_error', 'atoi', 'atoi_error', 'atol', 'atol_error', 'capitalize', 'capwords', 'center', 'count', 'digits', 'expandtabs', 'find', 'hexdigits', 'index', 'index_error', 'join', 'joinfields', 'letters', 'ljust', 'lower', 'lowercase', 'lstrip', 'maketrans', 'octdigits', 'printable', 'punctuation', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitfields', 'strip', 'swapcase', 'translate', 'upper', 'uppercase', 'whitespace', 'zfill']\n", "['ascii_lowercase', 'upper', '_re', 'letters', 'atol_error', 'lstrip', 'uppercase', 'ascii_letters', 'find', 'atof', 'replace', 'capwords', 'index_error', 'expandtabs', 'Template', 'strip', 'ascii_uppercase', 'octdigits', 'index', 'ljust', 'whitespace', '_int', 'rindex', '_float', 'punctuation', '__package__', 'printable', 'splitfields', 'split', 'rstrip', 'translate', '__doc__', '_multimap', 'count', 'joinfields', 'rjust', '__builtins__', '__file__', 'lower', 'swapcase', 'atof_error', 'atoi', 'hexdigits', 'Formatter', 'atol', '__name__', 'rsplit', '_idmapL', 'digits', 'lowercase', 'join', 'center', '_long', 'rfind', 'atoi_error', 'maketrans', 'capitalize', '_TemplateMetaclass', 'zfill', '_idmap']\n" ] } ], "source": [ "import string\n", "print dir(string)\n", "print string.__dict__.keys()" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "name = ascii_lowercase , type = \n", "name = upper , type = \n", "name = _re , type = \n", "name = letters , type = \n", "name = atol_error , type = \n", "name = lstrip , type = \n", "name = uppercase , type = \n", "name = ascii_letters , type = \n", "name = find , type = \n", "name = atof , type = \n", "name = replace , type = \n", "name = capwords , type = \n", "name = index_error , type = \n", "name = expandtabs , type = \n", "name = Template , type = \n", "name = strip , type = \n", "name = ascii_uppercase , type = \n", "name = octdigits , type = \n", "name = index , type = \n", "name = ljust , type = \n", "name = whitespace , type = \n", "name = _int , type = \n", "name = rindex , type = \n", "name = _float , type = \n", "name = punctuation , type = \n", "name = __package__ , type = \n", "name = printable , type = \n", "name = splitfields , type = \n", "name = split , type = \n", "name = rstrip , type = \n", "name = translate , type = \n", "name = __doc__ , type = \n", "name = _multimap , type = \n", "name = count , type = \n", "name = joinfields , type = \n", "name = rjust , type = \n", "name = __builtins__ , type = \n", "name = __file__ , type = \n", "name = lower , type = \n", "name = swapcase , type = \n", "name = atof_error , type = \n", "name = atoi , type = \n", "name = hexdigits , type = \n", "name = Formatter , type = \n", "name = atol , type = \n", "name = __name__ , type = \n", "name = rsplit , type = \n", "name = _idmapL , type = \n", "name = digits , type = \n", "name = lowercase , type = \n", "name = join , type = \n", "name = center , type = \n", "name = _long , type = \n", "name = rfind , type = \n", "name = atoi_error , type = \n", "name = maketrans , type = \n", "name = capitalize , type = \n", "name = _TemplateMetaclass , type = \n", "name = zfill , type = \n", "name = _idmap , type = \n" ] } ], "source": [ "for name, val in string.__dict__.items():\n", " print 'name = %-20s, type = %s' % (name, type(val))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2) 모듈의 재적재\n", "- 이미 메모리에 적재되어 있는 모듈은 다시 import 하더라도 기존에 적재되어 있는 모듈이 그대로 다시 이용된다." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "50.24\n", "6.2\n" ] } ], "source": [ "import mymath\n", "mymath.mypi = 6.2 # 값 수정(원래 모듈 파일에 정의된 값은 3.14)\n", "\n", "import mymath # 다시 import\n", "print mymath.mypi # 3.14가 아니라 6.2 -> 즉 이미 적재되어 있는 모듈 그냥 이용" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- reload(모듈)\n", " - 메모리에 등록된 것과 관계없이 해당 모듈의 파일에서 새롭게 다시 메모리에 재적재 시키는 내장 함수" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6.2\n", "50.24\n", "3.14\n" ] } ], "source": [ "print mymath.mypi\n", "reload(mymath)\n", "print mymath.mypi" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8. E-learning 15, 16 보충 자료" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1) 함수 정의시에 예상할 수 없는 키워드 인수 처리하기\n", "- 함수를 정의할 때 예측할 수 없는 인수를 선언하여 사전 타입으로 그러한 인수를 받을 수 있다.\n", " - 함수 정의시에 **var 형태의 인수 정의" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10 5\n", "{'depth': 10, 'diamension': 3}\n", "13\n" ] } ], "source": [ "def f(width, height, **kw):\n", " print width, height\n", " print kw\n", " value = 0\n", " for key in kw:\n", " value += kw[key]\n", " return value\n", "\n", "print f(width=10, height=5, depth=10, diamension=3)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10 5\n", "{'depth': 10, 'diamension': 3}\n", "13\n" ] } ], "source": [ "print f(10, 5, depth=10, diamension=3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 첫 두 개의 인수 다음에는 반드시 키워드 인수로만 함수 호출 가능" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "non-keyword arg after keyword arg (, line 1)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m print f(width=10, height=5, 10, 3)\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m non-keyword arg after keyword arg\n" ] } ], "source": [ "print f(width=10, height=5, 10, 3)" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "f() takes exactly 2 arguments (4 given)", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mprint\u001b[0m \u001b[0mf\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m10\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m5\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m10\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m3\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: f() takes exactly 2 arguments (4 given)" ] } ], "source": [ "print f(10, 5, 10, 3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 함수 선언시에 예상할 수 없는 키워드 인수는 맨 마지막에 선언해야 한다.\n", " - 함수 선언시 인수 선언 나열 방법\n", " - 일반 인수 -> 키워드 인수 -> 가변 인수 -> 예상치 못하는 키워드 인수" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 2\n", "(4, 5)\n", "{'c': 6, 'd': 7}\n" ] } ], "source": [ "def g(a, b, k = 1, *args, **kw):\n", " print a, b\n", " print args\n", " print kw\n", "\n", "g(1, 2, 3, 4, 5, c=6, d=7)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2) 함수 호출시에 사용 가능한 튜플 인수 및 사전 인수\n", "- 함수 호출에 사용될 인수값들이 튜플에 있다면 \"*튜플변수\"를 이용하여 함수 호출이 가능" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 2 3\n" ] } ], "source": [ "def h(a, b, c):\n", " print a, b, c\n", " \n", "args = (1, 2, 3)\n", "h(*args)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 함수 호출에 사용될 인수값들이 사전에 있다면 \"**사전변수\"를 이용하여 함수 호출이 가능" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 2 3\n" ] } ], "source": [ "dargs = {'a':1, 'b':2, 'c':3}\n", "h(**dargs)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 튜플 인수와 사전 인수를 동시에 사용" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 2 3\n" ] } ], "source": [ "args = (1,2)\n", "dargs = {'c':3}\n", "h(*args, **dargs)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3) 람다 함수 보충\n", "- 다음 4가지 프로그램은 동일함" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[60, 44, 30, 18, 8, 0, -6, -10, -12, -12, -10, -6, 0, 8, 18, 30, 44, 60, 78, 98]\n", "[-1000, -729, -512, -343, -216, -125, -64, -27, -8, -1, 0, 1, 8, 27, 64, 125, 216, 343, 512, 729]\n" ] } ], "source": [ "def f1(x):\n", " return x*x + 3*x - 10\n", "\n", "def f2(x):\n", " return x*x*x\n", "\n", "def g(func):\n", " return [func(x) for x in range(-10, 10)]\n", "\n", "print g(f1)\n", "print g(f2)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[60, 44, 30, 18, 8, 0, -6, -10, -12, -12, -10, -6, 0, 8, 18, 30, 44, 60, 78, 98]\n", "[-1000, -729, -512, -343, -216, -125, -64, -27, -8, -1, 0, 1, 8, 27, 64, 125, 216, 343, 512, 729]\n" ] } ], "source": [ "def g(func):\n", " return [func(x) for x in range(-10, 10)]\n", "\n", "print g(lambda x: x*x + 3*x - 10)\n", "print g(lambda x: x*x*x)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[60, 44, 30, 18, 8, 0, -6, -10, -12, -12, -10, -6, 0, 8, 18, 30, 44, 60, 78, 98]\n", "[-1000, -729, -512, -343, -216, -125, -64, -27, -8, -1, 0, 1, 8, 27, 64, 125, 216, 343, 512, 729]\n" ] } ], "source": [ "print [(lambda x: x*x + 3*x - 10)(x) for x in range(-10, 10)]\n", "print [(lambda x: x*x*x)(x) for x in range(-10, 10)]" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[60, 44, 30, 18, 8, 0, -6, -10, -12, -12, -10, -6, 0, 8, 18, 30, 44, 60, 78, 98]\n", "[-1000, -729, -512, -343, -216, -125, -64, -27, -8, -1, 0, 1, 8, 27, 64, 125, 216, 343, 512, 729]\n" ] } ], "source": [ "print map(lambda x: x*x + 3*x - 10, range(-10, 10))\n", "print map(lambda x: x*x*x, range(-10, 10))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4) map 및 filter 함수 보충" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- map함수에 시퀀스 자료형을 두 개 이상 할당할 수 있다.\n", " - 시퀀스 자료형이 n개 이면 function의 인자도 n개 이어야 함" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[7, 9, 11, 13, 15]\n", "[12, 15, 18]\n" ] } ], "source": [ "Y1 = map(lambda x, y: x + y, [1, 2, 3, 4, 5], [6, 7, 8, 9, 10])\n", "Y2 = map(lambda x, y, z: x + y + z, [1, 2, 3], [4, 5, 6], [7, 8, 9])\n", "print Y1\n", "print Y2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 두 개 이상의 시퀀스 자료형들에 대해 map 함수를 사용하여 순서쌍 만들기\n", " - function 인자를 None으로 할당" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['a', 'b', 'c', 'd']\n" ] } ], "source": [ "a = ['a', 'b', 'c', 'd']\n", "print map(None, a)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n" ] } ], "source": [ "a = ['a', 'b', 'c', 'd']\n", "b = [1, 2, 3, 4]\n", "print map(None, a, b)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[('a', 1, 5), ('b', 2, 6), ('c', 3, 7), ('d', 4, 8)]\n" ] } ], "source": [ "a = ['a', 'b', 'c', 'd']\n", "b = [1, 2, 3, 4]\n", "c = [5, 6, 7, 8]\n", "print map(None, a, b, c)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 두 개의 시퀀스 자료형의 원소의 개수가 다르면 부족한 원소에는 None을 할당" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[('a', 1), ('b', 2), (None, 3), (None, 4)]\n" ] } ], "source": [ "a = ['a', 'b']\n", "b = [1, 2, 3, 4]\n", "print map(None, a, b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 순서쌍을 만드는 전용 내장 함수 zip은 None을 추가하지 않고 짧은 인자를 기준으로 나머지는 버린다." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[('a', 1), ('b', 2)]\n" ] } ], "source": [ "a = ['a', 'b']\n", "b = [1, 2, 3, 4]\n", "print zip(a, b)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[(1, 4), (2, 5), (3, 6)]\n" ] } ], "source": [ "print zip([1, 2, 3], [4, 5, 6, 7, 8])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- filter의 첫 인자의 함수로서 None을 할당하면 seq 자료형에 있는 각 원소값 자체들을 평가하여 참인 것들만 필터링한다." ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['high', 'level', 'built-in', 'function', 10]\n" ] } ], "source": [ "L = ['high', False, 'level', '', 'built-in', '', 'function', 0, 10]\n", "L = filter(None, L)\n", "print L" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 6) 함수 객체의 속성\n", "- 함수도 객체이며 속성을 지닌다.\n", " - \\_\\_doc\\_\\_, func_doc: 문서 문자열\n", " - \\_\\_name\\_\\_, func_name: 함수 이름\n", " - func_defaults: 기본 인수 값들" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def f(a, b, c=1):\n", " 'func attribute testing'\n", " localx = 1\n", " localy = 2\n", " return 1 " ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "func attribute testing\n", "func attribute testing\n", "\n", "f\n", "f\n", "\n", "(1,)\n" ] } ], "source": [ "print f.__doc__ # 문서 문자열\n", "print f.func_doc\n", "print\n", "\n", "print f.__name__ # 함수의 이름\n", "print f.func_name\n", "print\n", "\n", "print f.func_defaults # 기본 인수값들" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7. E-learning 13, 14 보충 자료" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1) text file vs. binary file\n", "- 참고: http://stackoverflow.com/questions/2665866/what-is-the-wb-mean-in-this-code-using-python\n", "\n", " - On Unix systems (Linux, Mac OS X, etc.), binary mode does nothing - they treat text files the same way that any other files are treated. On Windows, however, text files are written with slightly modified line endings. This causes a serious problem when dealing with actual binary files, like exe or jpg files. Therefore, when opening files which are not supposed to be text, even in Unix, you should use wb or rb. Use plain w or r only for text files.\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2) with ~ as ~\n", "- 자동으로 자원 해제" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "s = \"\"\"Its power: Python developers typically report \n", "they are able to develop applications in a half\n", "to a tenth the amount of time it takes them to do\n", "the same work in such languages as C.\"\"\"\n", "with open('t.txt', 'w') as f: # f = open('t.txt', 'w')과 동일\n", " f.write(s) \n", " # f.close() 작성할 필요 없음. 자동으로 닫힘" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3) os.work" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import os\n", "os.chdir('/Users/yhhan/git/python-e-learning')\n", "print os.getcwd()\n", "print\n", "for path, subdirs, files in os.walk(os.getcwd()):\n", " print path, \" *** \", subdirs, \" *** \", files" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4) 프로그램 예제-1\n", "#### 임의의 텍스트 파일 내 문자 수를 출력하는 프로그램을 작성하라." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 해법 1" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "70122\n" ] } ], "source": [ "f = open('supplement-2016-09.ipynb')\n", "print len(f.read())\n", "f.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 해법 2" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "70122" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import os\n", "os.path.getsize('supplement-2016-09.ipynb')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 윈도우즈에서 만든 파일에 위 예제들을 수행하면 os.path.getsize('t.txt')가 라인수만큼 더 큼\n", " - 이유\n", " - 리눅스와 Mac에서는 라인 구분 제어 문자로 '\\012' 한 문자를 사용\n", " - 윈도우즈에서는 라인을 구분하는 제어 문자로 '\\015\\012' 두 개의 문자를 사용함" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'\\n'" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import os\n", "os.linesep" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- ![linesep](images/win_os_linesep.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 5) 프로그램 예제-2\n", "#### 임의의 텍스트 파일 내 단어 수를 출력하는 프로그램을 작성하라. 여기서 단어란, 공백으로 분리된 문자의 모임을 뜻한다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 해법 1" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8130\n" ] } ], "source": [ "f = open('supplement-2016-09.ipynb')\n", "s = f.read()\n", "n = len(s.split())\n", "print n\n", "f.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 해법 2" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8130\n" ] } ], "source": [ "n = len(open('supplement-2016-09.ipynb').read().split())\n", "print n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 6) 프로그램 예제-3\n", "#### 임의의 텍스트 파일 내 라인 수를 출력하는 프로그램을 작성하라." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 해법 1" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2570\n" ] } ], "source": [ "f = open('supplement-2016-09.ipynb')\n", "s = f.read()\n", "print s.count('\\n')\n", "f.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 해법 2" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2570\n" ] } ], "source": [ "f = open('supplement-2016-09.ipynb')\n", "print len(f.readlines())\n", "f.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 해법 3" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2570\n" ] } ], "source": [ "print open('supplement-2016-09.ipynb').read().count('\\n')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 해법 4" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2570\n" ] } ], "source": [ "print len(open('supplement-2016-09.ipynb').readlines())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 7) 다양한 파일 처리 모드" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- open 내장 함수의 두번째 인자 mode 설명\n", " - 두번째 인자 mode 생략시에는 읽기 전용(r) 모드로 설정\n", " \n", "| Mode | 간단 설명 | 자세한 설명\n", "|--------|-----------------------------|------------|\n", "| 'r' | 읽기 전용(기본 모드) | 파일 객체를 읽기 모드로 생성하고, 파일 포인터를 파일 처음 위치에 놓는다.|\n", "| 'w' | 쓰기 전용(기존 파일 내용 삭제) | 파일이 존재하지 않으면 새로운 파일을 쓰기 모드로 생성하고, 해당 파일이 이미 존재하면 내용을 모두 없에면서 쓰기 모드로 생성하고, 파일 포인터를 파일 처음 위치에 놓는다. |\n", "| 'a' | 파일 끝에 추가(쓰기 전용) | 파일이 존재하지 않으면 새롭게 파일을 생성하면서 쓰기 모드로 생성하고, 해당 파일이 이미 존재하면 파일 객체을 쓰기 모드로 생성하면서 파일 포인터를 파일의 마지막 위치에 놓는다 (그래서, 이후 작성되는 내용은 파일의 뒷 부분에 추가).|\n", "| 'r+' | 읽고 쓰기 | 파일 객체를 읽고 쓸 수 있도록 생성한다. 파일 포인터를 파일 처음 위치에 놓는다. |\n", "| 'w+' | 읽고 쓰기(기존 파일 내용 삭제) | 파일 객체를 읽고 쓸 수 있도록 생성한다. 파일이 존재하지 않으면 새로운 파일을 생성하고, 해당 파일이 이미 존재하면 내용을 모두 없에면서 생성하고, 파일 포인터를 파일 처음 위치에 놓는다.|\n", "| 'a+' | 읽고 쓰기(파일 끝에 추가) | 파일 객체를 읽고 쓸 수 있도록 생성한다. 파일이 존재하지 않으면 새롭게 파일을 생성하고, 해당 파일이 이미 존재하면 파일 객체을 생성하면서 파일 포인터를 파일의 마지막 위치에 놓는다 (그래서, 이후 작성되는 내용은 파일의 뒷 부분에 추가). |\n", "\n", "\n", " - 이진 파일로 저장을 위해서는 아래 모드 사용\n", "\n", "| Mode | 간단 설명 |\n", "|--------|-----------------------------|\n", "| 'rb' | 이진 파일 읽기 전용 |\n", "| 'wb' | 이진 파일 쓰기 전용(기존 파일 내용 삭제) |\n", "| 'ab' | 이진 파일 끝에 추가(쓰기 전용) |\n", "| 'rb+' | 이진 파일 읽고 쓰기 |\n", "| 'wb+' | 이진 파일 읽고 쓰기(기존 파일 내용 삭제) |\n", "| 'ab+' | 이진 파일 끝에 추가(읽기도 가능) |\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6. E-learning 11, 12 보충 자료" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1) 프로그램 예제\n", "- 100개의 소문자를 랜덤하게 생성하여 출력한다.\n", "- 생성된 각 소문자의 개수를 카운트하여 출력한다." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "e d t p p q d e l f q d w x h k r p c h\n", "j b a e p x o x z h d t i v w s y r p q\n", "e s y d f m e w l r u b l t j s h m r q\n", "r n l k g a d o o w r q p b u n e f g d\n", "i l g y u l r j z b p o d t u l e o u e\n", "\n", "a 2 b 4 c 1 d 8 e 8 f 3 g 3 h 4 i 2 j 3\n", "k 2 l 7 m 2 n 2 o 5 p 7 q 5 r 7 s 3 t 4\n", "u 5 v 1 w 4 x 3 y 3 z 2\n" ] } ], "source": [ "import random\n", "\n", "def getRandomLowerCaseLetter():\n", " return chr(random.randint(ord('a'), ord('z')))\n", "\n", "def createList():\n", " '''\n", " 소문자를 랜덤하게 생성하여 담은 리스트를 반환한다.\n", " '''\n", " chars = []\n", " \n", " for i in range(100):\n", " chars.append(getRandomLowerCaseLetter())\n", " \n", " #위 코드는 아래 코드와 동일\n", " #chars = [getRandomLowerCaseLetter() for i in range(100)]\n", " \n", " return chars\n", "\n", "def displayList(chars):\n", " '''\n", " 리스트에 포함된 문자를 한 행에 20개씩 출력한다.\n", " '''\n", " for i in range(len(chars)):\n", " if (i + 1) % 20 == 0:\n", " print chars[i]\n", " else:\n", " print chars[i],\n", "\n", "def countLetters(chars):\n", " '''\n", " 0으로 초기화된 26개의 정수리스트를 생성한 후 인자로 주어진 chars에 있는 각 문자들의 개수를 저장한다.\n", " '''\n", " counts = [0] * 26\n", " \n", " for i in range(len(chars)):\n", " counts[ord(chars[i]) - ord('a')] += 1 \n", " \n", " return counts\n", "\n", "def displayCounts(counts):\n", " '''\n", " 각 문자별로 카운트를 한 행에 10개씩 출력한다.\n", " '''\n", " for i in range(len(counts)):\n", " if (i + 1) % 10 == 0:\n", " print chr(i + ord('a')), counts[i]\n", " else:\n", " print chr(i + ord('a')), counts[i],\n", "\n", "if __name__ == '__main__':\n", " chars = createList()\n", " displayList(chars)\n", " print\n", " counts = countLetters(chars)\n", " displayCounts(counts)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2) 집합의 성능" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[5601, 7177, 661, 7579, 347, 6173, 2121, 4834, 2932, 9408]\n", "The elapsed time to check into a set is 4 ms\n", "The elapsed time to check into a list is 1204 ms\n", "The elapsed time to remove each element from a set is 2 ms\n", "The elapsed time to remove each element from a list is 488 ms\n" ] } ], "source": [ "import random\n", "import time\n", "\n", "NUMBER_OF_ELEMENTS = 10000\n", "\n", "lst = list(range(NUMBER_OF_ELEMENTS))\n", "random.shuffle(lst)\n", "print lst[0:10]\n", "\n", "s = set(lst)\n", "\n", "# 해당 원소가 집합/리스트에 포함되어 있는지 검사\n", "startTime = time.time()\n", "for i in range(NUMBER_OF_ELEMENTS):\n", " i in s\n", "endTime = time.time()\n", "runTime = int((endTime - startTime) * 1000)\n", "print 'The elapsed time to check into a set is %s ms' % runTime\n", "\n", "startTime = time.time()\n", "for i in range(NUMBER_OF_ELEMENTS):\n", " i in lst\n", "endTime = time.time()\n", "runTime = int((endTime - startTime) * 1000)\n", "print 'The elapsed time to check into a list is %s ms' % runTime\n", "\n", "# 해당 원소를 집합/리스트로 부터 제거\n", "startTime = time.time()\n", "for i in range(NUMBER_OF_ELEMENTS):\n", " s.remove(i)\n", "endTime = time.time()\n", "runTime = int((endTime - startTime) * 1000)\n", "print 'The elapsed time to remove each element from a set is %s ms' % runTime\n", "\n", "startTime = time.time()\n", "for i in range(NUMBER_OF_ELEMENTS):\n", " lst.remove(i)\n", "endTime = time.time()\n", "runTime = int((endTime - startTime) * 1000)\n", "print 'The elapsed time to remove each element from a list is %s ms' % runTime" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3) 단어 세기\n", "- 다음 주어진 문자열 s에서 ,와 .을 제거하고\n", "- 모든 문자를 소문자로 변경하고\n", "- 각각의 단어의 출현 빈도를 출력하시오." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "and : 2\n", "it : 2\n", "existing : 1\n", "in : 1\n", "for : 1\n", "start : 1\n", "enviroment : 1\n", "to : 3\n", "new : 1\n", "development : 1\n", "we : 1\n", "creating : 1\n", "python : 1\n", "propose : 1\n", "possible : 1\n", "focus : 1\n", "teaching : 1\n", "teach : 1\n", "an : 1\n", "by : 1\n", "a : 1\n", "on : 1\n", "language : 1\n", "programming : 1\n", "materials : 1\n", "making : 1\n", "scripting : 1\n" ] } ], "source": [ "# -*-coding:utf-8 -*-\n", "s = \"We propose to start by making it possible to teach progra\\\n", "mming in python, an existing scripting language, and to focus \\\n", "on creating a new development enviroment and teaching \\\n", "materials for it.\"\n", " \n", "# 대치 과정\n", "s=s.replace(',','')\n", "s=s.replace('.','')\n", "s=s.lower()\n", " \n", "#공백 단위로 단어 쪼개고 단어 넣을 딕셔너리 선언\n", "listSplited = s.split()\n", "words = {}\n", " \n", "#단어 쪼개놓은 리스트에서 각각 단어의 개수 세기\n", "for i in listSplited:\n", " if not i in words.keys():\n", " words[i]=1\n", " else:\n", " words[i]=words[i]+1\n", " \n", "#포맷을 이용한 출력\n", "format = \"%s : %d\"\n", " \n", "for i in words:\n", " print format % (i, words[i])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5. E-learning 9, 10 보충 자료\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1) 리스트를 배열처럼 활용하기\n", "- 1차원 배열처럼 활용하기" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3, 4, 5]\n", "1\n", "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "2\n" ] } ], "source": [ "a = [1, 2, 3, 4, 5]\n", "b = range(10)\n", "print a\n", "print a[0]\n", "print b\n", "print b[2]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 0으로 초기화된 사이즈 10인 1차원 배열 생성" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [0] * 10\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 2차원 배열처럼 활용하기" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n", "6\n" ] } ], "source": [ "mat = [[1, 2, 3],\n", " [4, 5, 6],\n", " [7, 8, 9]]\n", "print mat\n", "print mat[1][2]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2) 리스트 내포\n", "- 다음은 고등학교 수학에서 배운 집합의 표기 방법이다.\n", " - A = {x^2 | x in {0, ..., 9}}\n", " - B = {1, 2, 4, 8, 16, ..., 2^16}\n", " - C = {x | x in S and x is odd}\n", "\n", "- 파이썬의 리스트 내포(list comprehension)는 바로 위 집합 표기법과 유사한 방식의 리터럴이다. \n", "- 위 집합들을 리스트 내포 방식으로 표현하면 다음과 같다. \n", " - A = [x**2 for x in range(10)]\n", " - B = [2**i for i in range(17)]\n", " - C = [x for x in S if x % 2 == 1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 예 1. 피타고라스 삼각형의 각 3변의 길이 리스트 (조건: 각 변 x, y, z의 길이는 30 보다 작아야 하며, x <= y <= z 이어야 함)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[(3, 4, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25), (8, 15, 17), (9, 12, 15), (10, 24, 26), (12, 16, 20), (15, 20, 25), (20, 21, 29)]\n" ] } ], "source": [ "k = [(x,y,z) for x in range(1,30) for y in range(x,30) for z in range(y,30) if x**2 + y**2 == z**2]\n", "print k" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 바로 위 코드는 아래와 동일하다." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[(3, 4, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25), (8, 15, 17), (9, 12, 15), (10, 24, 26), (12, 16, 20), (15, 20, 25), (20, 21, 29)]\n" ] } ], "source": [ "l = []\n", "for x in range(1,30):\n", " for y in range(x,30):\n", " for z in range (y, 30):\n", " if x**2 + y**2 == z**2:\n", " l.append((x, y, z))\n", "print l" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 예 2. 중첩 리스트 내포" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['AC', 'AD', 'BC', 'BD']\n", "\n", "[['AC', 'BC'], ['AD', 'BD']]\n" ] } ], "source": [ "list_a = ['A', 'B']\n", "list_b = ['C', 'D']\n", "print [x + y for x in list_a for y in list_b]\n", "print\n", "print [[x + y for x in list_a] for y in list_b]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 바로 위 코드는 아래와 동일하다." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[['AC', 'BC'], ['AD', 'BD']]\n" ] } ], "source": [ "l = []\n", "for y in list_b:\n", " l2 = []\n", " for x in list_a:\n", " l2.append(x+y)\n", " l.append(l2)\n", "print l" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 예 3. 리스트 내포를 활용한 2차원 배열 생성" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]\n", "[[100, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]\n" ] } ], "source": [ "mat = [ [0]*4 for x in range(3)]\n", "print mat\n", "\n", "mat[0][0] = 100\n", "print mat" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3) 특별 속성\n", "- 특별 속성: 파이썬 내에 존재하는 모든 객체 마다 부여되는 특별한 Read-only 속성\n", " - [참고]: https://docs.python.org/2/library/stdtypes.html#object.__dict__" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "__main__\n", "\n", "Automatically created module for IPython interactive environment\n", "\n" ] } ], "source": [ "print __name__ # 로컬 이름 \n", "print\n", "\n", "print __doc__ # 로컬에 지정된 문서문자열\n", "print" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "math.__name__: math\n", "\n", "math.__doc__: This module is always available. It provides access to the\n", "mathematical functions defined by the C standard.\n", "\n", "math.log10.__name__: log10\n", "\n", "math.log10.__doc__: log10(x)\n", "\n", "Return the base 10 logarithm of x.\n", "\n", "\n" ] } ], "source": [ "import math\n", "\n", "print \"math.__name__: \", math.__name__\n", "print\n", "print \"math.__doc__:\", math.__doc__\n", "print\n", "print \"math.log10.__name__: \", math.log10.__name__\n", "print\n", "print \"math.log10.__doc__: \", math.log10.__doc__\n", "print\n", "print type(math.log10)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": true }, "outputs": [], "source": [ "? math.log10" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. E-learning 7, 8 보충 자료\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1) unicode 추가 설명" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "a = unicode(\"한글과 세종대왕\", 'utf-8')\n", "b = u\"한글과 세종대왕\"" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "False\n" ] } ], "source": [ "print a == b\n", "print a is b" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "65\n", "A\n" ] } ], "source": [ "print ord('A') # ord(): 문자의 ASCII 코드값 반환\n", "print chr(65) # char(): ASCII 코드 65를 지니는 문자를 반환" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "http://www.fileformat.info/info/unicode/char/ac00/index.htm" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "가\n", "가\n" ] } ], "source": [ "print unichr(0xac00) # unichr(): UNICODE 코드 0xac00를 지니는 문자를 반환\n", "print unichr(44032) " ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "가 각 갂 갃 간 갅 갆 갇 갈 갉 갊 갋 갌 갍 갎 갏 감 갑 값 갓 갔 강 갖 갗 갘 같 갚 갛 개 객 갞 갟 갠 갡 갢 갣 갤 갥 갦 갧 갨 갩 갪 갫 갬 갭 갮 갯 갰 갱 갲 갳 갴 갵 갶 갷 갸 갹 갺 갻 갼 갽 갾 갿 걀 걁 걂 걃 걄 걅 걆 걇 걈 걉 걊 걋 걌 걍 걎 걏 걐 걑 걒 걓 걔 걕 걖 걗 걘 걙 걚 걛 걜 걝 걞 걟 걠 걡 걢 걣 걤 걥 걦 걧 걨 걩 걪 걫 걬 걭 걮 걯 거 걱 걲 걳 건 걵 걶 걷 걸 걹 걺 걻 걼 걽 걾 걿 검 겁 겂 것 겄 겅 겆 겇 겈 겉 겊 겋 게 겍 겎 겏 겐 겑 겒 겓 겔 겕 겖 겗 겘 겙 겚 겛 겜 겝 겞 겟 겠 겡 겢 겣 겤 겥 겦 겧 겨 격 겪 겫 견 겭 겮 겯 결 겱 겲 겳 겴 겵 겶 겷 겸 겹 겺 겻 겼 경 겾 겿 곀 곁 곂 곃 계 곅 곆 곇 곈 곉 곊 곋 곌 곍 곎 곏 곐 곑 곒 곓 곔 곕 곖 곗 곘 곙 곚 곛 곜 곝 곞 곟 고 곡 곢 곣 곤 곥 곦 곧 골 곩 곪 곫 곬 곭 곮 곯 곰 곱 곲 곳 곴 공 곶 곷 곸 곹 곺 곻 과 곽 곾 곿 관 괁 괂 괃 괄 괅 괆 괇 괈 괉 괊 괋 괌 괍 괎 괏 괐 광 괒 괓 괔 괕 괖 괗 괘 괙 괚 괛 괜 괝 괞 괟 괠 괡 괢 괣 괤 괥 괦 괧 괨 괩 괪 괫 괬 괭 괮 괯 괰 괱 괲 괳 괴 괵 괶 괷 괸 괹 괺 괻 괼 괽 괾 괿 굀 굁 굂 굃 굄 굅 굆 굇 굈 굉 굊 굋 굌 굍 굎 굏 교 굑 굒 굓 굔 굕 굖 굗 굘 굙 굚 굛 굜 굝 굞 굟 굠 굡 굢 굣 굤 굥 굦 굧 굨 굩 굪 굫 구 국 굮 굯 군 굱 굲 굳 굴 굵 굶 굷 굸 굹 굺 굻 굼 굽 굾 굿 궀 궁 궂 궃 궄 궅 궆 궇 궈 궉 궊 궋 권 궍 궎 궏 궐 궑 궒 궓 궔 궕 궖 궗 궘 궙 궚 궛 궜 궝 궞 궟 궠 궡 궢 궣 궤 궥 궦 궧 궨 궩 궪 궫 궬 궭 궮 궯 궰 궱 궲 궳 궴 궵 궶 궷 궸 궹 궺 궻 궼 궽 궾 궿 귀 귁 귂 귃 귄 귅 귆 귇 귈 귉 귊 귋 귌 귍 귎 귏 귐 귑 귒 귓 귔 귕 귖 귗 귘 귙 귚 귛 규 귝 귞 귟 균 귡 귢 귣 귤 귥 귦 귧 귨 귩 귪 귫 귬 귭 귮 귯 귰 귱 귲 귳 귴 귵 귶 귷 그 극 귺 귻 근 귽 귾 귿 글 긁 긂 긃 긄 긅 긆 긇 금 급 긊 긋 긌 긍 긎 긏 긐 긑 긒 긓 긔 긕 긖 긗 긘 긙 긚 긛 긜 긝 긞 긟 긠 긡 긢 긣 긤 긥 긦 긧 긨 긩 긪 긫 긬 긭 긮 긯 기 긱 긲 긳 긴 긵 긶 긷 길 긹 긺 긻 긼 긽 긾 긿 김 깁 깂 깃 깄 깅 깆 깇 깈 깉 깊 깋 까 깍 깎 깏 깐 깑 깒 깓 깔 깕 깖 깗 깘 깙 깚 깛 깜 깝 깞 깟 깠 깡 깢 깣 깤 깥 깦 깧 깨 깩 깪 깫 깬 깭 깮 깯 깰 깱 깲 깳 깴 깵 깶 깷 깸 깹 깺 깻 깼 깽 깾 깿 꺀 꺁 꺂 꺃 꺄 꺅 꺆 꺇 꺈 꺉 꺊 꺋 꺌 꺍 꺎 꺏 꺐 꺑 꺒 꺓 꺔 꺕 꺖 꺗 꺘 꺙 꺚 꺛 꺜 꺝 꺞 꺟 꺠 꺡 꺢 꺣 꺤 꺥 꺦 꺧 꺨 꺩 꺪 꺫 꺬 꺭 꺮 꺯 꺰 꺱 꺲 꺳 꺴 꺵 꺶 꺷 꺸 꺹 꺺 꺻 꺼 꺽 꺾 꺿 껀 껁 껂 껃 껄 껅 껆 껇 껈 껉 껊 껋 껌 껍 껎 껏 껐 껑 껒 껓 껔 껕 껖 껗 께 껙 껚 껛 껜 껝 껞 껟 껠 껡 껢 껣 껤 껥 껦 껧 껨 껩 껪 껫 껬 껭 껮 껯 껰 껱 껲 껳 껴 껵 껶 껷 껸 껹 껺 껻 껼 껽 껾 껿 꼀 꼁 꼂 꼃 꼄 꼅 꼆 꼇 꼈 꼉 꼊 꼋 꼌 꼍 꼎 꼏 꼐 꼑 꼒 꼓 꼔 꼕 꼖 꼗 꼘 꼙 꼚 꼛 꼜 꼝 꼞 꼟 꼠 꼡 꼢 꼣 꼤 꼥 꼦 꼧 꼨 꼩 꼪 꼫 꼬 꼭 꼮 꼯 꼰 꼱 꼲 꼳 꼴 꼵 꼶 꼷 꼸 꼹 꼺 꼻 꼼 꼽 꼾 꼿 꽀 꽁 꽂 꽃 꽄 꽅 꽆 꽇 꽈 꽉 꽊 꽋 꽌 꽍 꽎 꽏 꽐 꽑 꽒 꽓 꽔 꽕 꽖 꽗 꽘 꽙 꽚 꽛 꽜 꽝 꽞 꽟 꽠 꽡 꽢 꽣 꽤 꽥 꽦 꽧 꽨 꽩 꽪 꽫 꽬 꽭 꽮 꽯 꽰 꽱 꽲 꽳 꽴 꽵 꽶 꽷 꽸 꽹 꽺 꽻 꽼 꽽 꽾 꽿 꾀 꾁 꾂 꾃 꾄 꾅 꾆 꾇 꾈 꾉 꾊 꾋 꾌 꾍 꾎 꾏 꾐 꾑 꾒 꾓 꾔 꾕 꾖 꾗 꾘 꾙 꾚 꾛 꾜 꾝 꾞 꾟 꾠 꾡 꾢 꾣 꾤 꾥 꾦 꾧 꾨 꾩 꾪 꾫 꾬 꾭 꾮 꾯 꾰 꾱 꾲 꾳 꾴 꾵 꾶 꾷 꾸 꾹 꾺 꾻 꾼 꾽 꾾 꾿 꿀 꿁 꿂 꿃 꿄 꿅 꿆 꿇 꿈 꿉 꿊 꿋 꿌 꿍 꿎 꿏 꿐 꿑 꿒 꿓 꿔 꿕 꿖 꿗 꿘 꿙 꿚 꿛 꿜 꿝 꿞 꿟 꿠 꿡 꿢 꿣 꿤 꿥 꿦 꿧\n" ] } ], "source": [ "i = 0\n", "while i < 1000:\n", " print unichr(0xac00 + i),\n", " i = i + 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2) str()과 repr()의 차이\n", "- str(): 객체의 비공식적인 (informal) 문자열 표현 - 가능하면 읽기 편하게...\n", "- repr(): 객체의 공식적인 (official) 문자열 표현 - 가능하면 실제 객체를 완벽하게 표현할 수 있도록...\n", "- [참고] http://pinocc.tistory.com/168" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.23456789123\n", "1.23456789123\n", "1.234567891234568\n" ] } ], "source": [ "f = 1.23456789123456789\n", "print f\n", "print str(f)\n", "print repr(f) # repr()은 유효 숫자를 길게 출력" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.23456789123, 1.234567891234568\n" ] } ], "source": [ "print \"%s, %r\" % (f, f) # str()과 repr() 호출" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1, 2) -- [3, 4, 5]\n" ] } ], "source": [ "print \"%s -- %s\" % ((1, 2), [3, 4, 5]) # str() 호출" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1, 2) -- [3, 4, 5]\n" ] } ], "source": [ "print \"%r -- %r\" % ((1, 2), [3, 4, 5]) # str() 대신에 repr() 내장 함수 사용" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.3\n", "0.3\n" ] } ], "source": [ "g = 0.3\n", "print str(g)\n", "print repr(g)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello\n", "'Hello'\n" ] } ], "source": [ "h = 'Hello'\n", "print str(h)\n", "print repr(h)" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'Hello' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mx\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0meval\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mstr\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mh\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n", "\u001b[0;31mNameError\u001b[0m: name 'Hello' is not defined" ] } ], "source": [ "x = eval(str(h))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- repr() 내장함수에 의하여 반환된 문자열은 eval() 내장함수에 의하여 Evaluation이 가능함 " ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": true }, "outputs": [], "source": [ "x = eval(repr(h))" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6\n" ] } ], "source": [ "a = '1 + 2 + 3'\n", "b = eval(a)\n", "print b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3) [중요] 문서 문자열 (Documentation String, docstring)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def add(a, b):\n", " \"add(a, b) returns a+b\"\n", " return a + b" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "add(a, b) returns a+b\n" ] } ], "source": [ "print add.__doc__" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function add in module __main__:\n", "\n", "add(a, b)\n", " add(a, b) returns a+b\n", "\n" ] } ], "source": [ "help(add)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": true }, "outputs": [], "source": [ "? add" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4) string 모듈 상수" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0123456789\n", "01234567\n", "0123456789abcdefABCDEF\n", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\n", "abcdefghijklmnopqrstuvwxyz\n", "ABCDEFGHIJKLMNOPQRSTUVWXYZ\n", "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\n", "\n", "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n", "\r", "\u000b", "\f", "\n", "\t\n", "\u000b", "\f", "\r", " \n" ] } ], "source": [ "import string\n", "\n", "print string.digits\n", "print string.octdigits\n", "print string.hexdigits\n", "print string.letters\n", "print string.lowercase\n", "print string.uppercase\n", "print string.punctuation # 각종 기호들\n", "print\n", "print string.printable # 인쇄 가능한 모든 문자들\n", "print string.whitespace # 공백 문자들 '\\011\\012\\013\\014\\015'" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "True\n" ] } ], "source": [ "x = 'a'\n", "print x in string.uppercase\n", "print x in string.lowercase" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\n" ] } ], "source": [ "d = string.letters + string.digits\n", "print d" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "your id:3##\n" ] } ], "source": [ "userid = raw_input('your id:')" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "invalid user id\n" ] } ], "source": [ "d = string.letters + string.digits\n", "for ch in userid:\n", " if ch not in d:\n", " print 'invalid user id'\n", " break" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 5) [중요] 문자열 붙이기 코딩 방법 비교" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.534403085709\n" ] } ], "source": [ "import time\n", "start_time = time.time()\n", "s = ''\n", "for k in range(1000000):\n", " s += 'python'\n", "end_time = time.time()\n", "print end_time - start_time" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.396770954132\n" ] } ], "source": [ "start_time = time.time()\n", "t = []\n", "for k in range(1000000):\n", " t.append('python')\n", "s = ''.join(t)\n", "end_time = time.time()\n", "print end_time - start_time" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.00274300575256\n" ] } ], "source": [ "start_time = time.time()\n", "s = 'python' * 1000000\n", "end_time = time.time()\n", "print end_time - start_time" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. E-learning 5, 6 보충 자료" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1) 조심해야 할 나누기 연산 " ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "1.25\n", "\n", "-2\n", "-1.25\n" ] } ], "source": [ "print 5 / 4 # 자동으로 floor 처리 됨\n", "print 5.0 / 4\n", "print\n", "print -5 / 4 # 자동으로 floor 처리 됨\n", "print -5.0 / 4" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- //: floor division\n", " - 그러므로 '정수 // 정수' 결과는 '정수 / 정수'와 항상 동일 \n", " - 하지만 실수에 대한 // 연산 결과는 floor division 이므로 정수형 실수로 결과나 나옴" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.5\n", "0.0\n", "\n", "1.25\n", "1.0\n", "1\n", "1\n", "\n", "-1.25\n", "-2.0\n", "-2\n", "-2\n" ] } ], "source": [ "print 1.0 / 2\n", "print 1.0 // 2 # floor division\n", "print\n", "print 5.0 / 4\n", "print 5.0 // 4 # floor division\n", "print 5 / 4\n", "print 5 // 4 # floor division\n", "print \n", "print -5.0 / 4\n", "print -5.0 // 4 # floor division\n", "print -5 / 4\n", "print -5 // 4 # floor division" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2) 함수 내 디폴트 인자 선언시 조심할 점" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "non-default argument follows default argument (, line 1)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m def incr(x=1, y): # 디폴트 인자 뒤에 정상적인 인자 선언 안됨\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m non-default argument follows default argument\n" ] } ], "source": [ "def incr(x=1, y): # 디폴트 인자 뒤에 정상적인 인자 선언 안됨\n", " return x + y\n", "\n", "print incr(5)\n", "\n", "print incr(5, 10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3) 유용한 모듈 학습: 시각 다루기" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1475076684.95\n", "\n", "\n", "totalSeconds - 1475076684\n", "totalMinutes - 24584611\n", "totalHours - 409743\n", "현재 시각은 15 : 31 : 24 GMT 입니다.\n" ] } ], "source": [ "import time\n", "\n", "currentTime = time.time() # Unix Epoch 부터 현재까지 경과된 시각 (GMT/UST 기준)을 실수형 초 단위로 최대한 정확하게 얻어온다.\n", "print currentTime\n", "print type(currentTime)\n", "print\n", "\n", "totalSeconds = int(currentTime) # 1970년 1월 1일 0시 이후부터 현재시각까지의 정수형 초 값을 얻어온다.\n", "print \"totalSeconds -\", totalSeconds\n", "currentSecond = totalSeconds % 60 # 현재 시각의 초 값을 얻어온다.\n", "\n", "totalMinutes = totalSeconds // 60 # 전체 분 값을 계산한다. \n", "print \"totalMinutes -\", totalMinutes\n", "currentMinute = totalMinutes % 60 # 현재 시각의 분 값을 얻어온다.\n", "\n", "totalHours = totalMinutes // 60 # 전체 시 값을 계산한다.\n", "print \"totalHours -\", totalHours\n", "currentHours = totalHours % 24 # 현재 시각의 시 값을 얻어온다.\n", "\n", "print \"현재 시각은\", currentHours, \":\", currentMinute, \":\", currentSecond, \"GMT 입니다.\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 대한민국의 Time Zone 및 로컬타임 얻기" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "('KST', 'KST')\n", "\n", "time.struct_time(tm_year=2016, tm_mon=9, tm_mday=29, tm_hour=0, tm_min=31, tm_sec=19, tm_wday=3, tm_yday=273, tm_isdst=0)\n" ] } ], "source": [ "print time.tzname\n", "print\n", "localtime = time.localtime()\n", "print localtime" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3) 코드 학습: 숫자 맞추기 게임 소스" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello! What is your name?\n", "YHHAN\n", "Well, YHHAN, I am thinking of a number between 1 and 20.\n", "Take a guess.\n", "10\n", "Your guess is too low.\n", "Take a guess.\n", "15\n", "Good job, YHHAN! You guessed my number in 2 guesses!\n" ] } ], "source": [ "# This is a guess the number game.\n", "import random\n", "\n", "guessesTaken = 0\n", "\n", "print('Hello! What is your name?')\n", "myName = raw_input()\n", "\n", "number = random.randint(1, 20) # return random integer in range [a, b], including both end points.\n", "print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')\n", "\n", "while guessesTaken < 6:\n", " print('Take a guess.') \n", " guess = int(input())\n", "\n", " guessesTaken = guessesTaken + 1\n", "\n", " if guess < number:\n", " print('Your guess is too low.')\n", "\n", " if guess > number:\n", " print('Your guess is too high.')\n", "\n", " if guess == number:\n", " break\n", "\n", "if guess == number:\n", " guessesTaken = str(guessesTaken)\n", " print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')\n", "\n", "if guess != number:\n", " number = str(number)\n", " print('Nope. The number I was thinking of was ' + number)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. E-learning 3, 4 보충 자료" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1) 파이썬에서 지원하는 각종 타입들 알아보기" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['BooleanType',\n", " 'BufferType',\n", " 'BuiltinFunctionType',\n", " 'BuiltinMethodType',\n", " 'ClassType',\n", " 'CodeType',\n", " 'ComplexType',\n", " 'DictProxyType',\n", " 'DictType',\n", " 'DictionaryType',\n", " 'EllipsisType',\n", " 'FileType',\n", " 'FloatType',\n", " 'FrameType',\n", " 'FunctionType',\n", " 'GeneratorType',\n", " 'GetSetDescriptorType',\n", " 'InstanceType',\n", " 'IntType',\n", " 'LambdaType',\n", " 'ListType',\n", " 'LongType',\n", " 'MemberDescriptorType',\n", " 'MethodType',\n", " 'ModuleType',\n", " 'NoneType',\n", " 'NotImplementedType',\n", " 'ObjectType',\n", " 'SliceType',\n", " 'StringType',\n", " 'StringTypes',\n", " 'TracebackType',\n", " 'TupleType',\n", " 'TypeType',\n", " 'UnboundMethodType',\n", " 'UnicodeType',\n", " 'XRangeType',\n", " '__all__',\n", " '__builtins__',\n", " '__doc__',\n", " '__file__',\n", " '__name__',\n", " '__package__']" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import types\n", "\n", "dir(types)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "True\n", "True\n", "True\n", "True\n", "True\n" ] } ], "source": [ "print type(123) is types.IntType\n", "print type(123.0) is types.FloatType\n", "print type('abc') is types.StringType\n", "print type([]) is types.ListType\n", "print type(()) is types.TupleType\n", "print type({}) is types.DictionaryType" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2) 레퍼런스 카운트 (Reference Count)와 쓰레기 수집 (Garbage Collection) " ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": true }, "outputs": [], "source": [ "x = y = z = 100" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![image](images/referenceCount1.png)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": true }, "outputs": [], "source": [ "del x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![image](images/referenceCount2.png)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": true }, "outputs": [], "source": [ "y = 200\n", "z = 300" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![image](images/referenceCount3.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 레퍼런스 카운트를 얻는 법\n", " - sys 모듈의 getrefcount() 함수: 함수 수행 결과의 레퍼런스 카운트가 생각보다 큰 이유 --> 본 함수가 작업 처리를 하기 위해서 순간적으로 레퍼런스가 증가할 수도 있고, 파이썬 가상머신 자체가 관리의 용도로 레퍼런스를 지니고 있을 수 있음" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "\n", "4\n", "4\n", "\n", "5\n", "5\n", "5\n" ] } ], "source": [ "import sys\n", "\n", "a1 = 191919\n", "print sys.getrefcount(a1) # 새로운 191919 객체를 만들고 이 객체에 대한 reference count 반환\n", "\n", "print\n", "\n", "a2 = a1\n", "print sys.getrefcount(a1) # a1과 a3가 참조하는 객체는 동일하며, reference count는 기존보다 1이 증가되어 있음 \n", "print sys.getrefcount(a2) # a2는 여전히 reference count가 이전 값과 동일함\n", "print\n", "\n", "aa1 = aa2 = aa3 = 202020\n", "print sys.getrefcount(aa1)\n", "print sys.getrefcount(aa2)\n", "print sys.getrefcount(aa3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "4) [참고] turtle 모듈 활용하기\n", "- https://opentechschool.github.io/python-beginners/ko/simple_drawing.html\n", "- http://openbookproject.net/thinkcs/python/english3e/hello_little_turtles.html\n", "- https://www.youtube.com/watch?v=vEkiaHtdwIk\n", "- https://python-turtle-demo.googlecode.com/files/SevenWaysToUseTurtle-PyCon2009.pdf" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import turtle\n", "\n", "t = turtle.Turtle()\n", "t.shape(\"turtle\")\n", "t.color(\"blue\")\n", "\n", "t.pensize(3) # 펜 사이즈를 3으로 설정한다.\n", "t.penup() # 펜을 종이로 부터 들어올린다.\n", "t.goto(-200, -50) # 해당 좌표로 이동한다.\n", "t.pendown() # 펜을 종이에 놓는다.\n", "t.circle(40, steps=3) # 반지름이 40인 원을 3 step으로만 그린다. ==> 삼각형이 그려짐\n", "\n", "t.penup()\n", "t.goto(-100, -50)\n", "t.pendown()\n", "t.circle(40, steps=4)\n", "\n", "t.penup()\n", "t.goto(0, -50)\n", "t.pendown()\n", "t.circle(40, steps=5)\n", "\n", "t.penup()\n", "t.goto(100, -50)\n", "t.pendown()\n", "t.circle(40, steps=6)\n", "\n", "t.penup()\n", "t.goto(200, -50)\n", "t.pendown()\n", "t.circle(40, steps=40)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Turtle의 펜 그리기 상태 메소드

\n", " \n", "| 메소드 명 | 설명 | \n", "| ---------- | :--------- |\n", "|turtle.pendown()|펜을 내려놓는다 - 움직일 때 그려진다.|\n", "|turtle.penup()|펜을 들어올린다 - 움직일 때 그려지지 않는다.|\n", "|turtle.pensize()|선의 두께를 특정 폭으로 설정한다.|" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Turtle의 이동 메소드

\n", "\n", "|
메소드 명
|
설명
| \n", "| ---------- | :--------- |\n", "|turtle.forward(d)|turtle이 향하고 있는 방향으로 특정 거리 d만큼 앞으로 이동시킨다.|\n", "|turtle.backward(d)|turtle이 향하고 있는 반대 방향으로 특정 거리 d만큼 뒤로 이동시킨다. turtle의 방향은 바뀌지 않는다.|\n", "|turtle.right(angle)|turtle을 특정 각만큼 오른쪽으로 회전시킨다.|\n", "|turtle.left(angle)|turtle을 특정 각만큼 왼쪽으로 회전시킨다.|\n", "|turtle.goto(x,y)|turtle을 절대 위치 (x,y)로 옮긴다.|\n", "|turtle.setx(x)|turtle의 x 좌표를 특정 위치로 옮긴다.|\n", "|turtle.setx(y)|turtle의 y 좌표를 특정 위치로 옮긴다.|\n", "|turtle.setheading(angle)|특정 각도로 turtle의 방향을 설정한다. 0-동쪽, 90-북쪽, 180-서쪽, 270-남쪽.|\n", "|turtle.home()|turtle을 원점 (0,0)으로 옮기고 동쪽 방향으로 설정한다.|\n", "|turtle.circle(r, ext, steps)|특정 반지름 r, 경계 ext와 단계 step인 원을 그린다.|\n", "|turtle.dot(diameter, color)|특정 지름 diameter와 색상 color인 원을 그린다.|\n", "|turtle.undo()|turtle의 마지막 명령을 (반복적으로)되돌린다.|\n", "|turtle.speed(s)|1부터 10사이의 정수(10이 최대) s로 turtle의 속도를 설정한다.|\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Turtle 펜 색상, 채우기와 그리기 메소드

\n", "\n", "|
메소드 명
|
설명
|\n", "| ---------- | :--------- |\n", "|turtle.color(c)|펜 색상을 c로 설정한다.|\n", "|turtle.fillcolor(c)|펜 채우기 색상을 c로 설정한다.|\n", "|turtle.begin_fill()|도형을 채우기 전에 이 메소드를 호출한다.|\n", "|turtle.end_fill()|begin_fill에 대한 마지막 호출전까지 그려진 도형을 채운다.|\n", "|turtle.filling()|채우기 상태를 반환한다. 채우기 상태이면 True, 그렇지 않으면 False|\n", "|turtle.clear()|창을 깨끗하게 지운다. turtle의 상태와 위치는 영향을 받지 않는다.|\n", "|turtle.reset()|창을 깨끗하게 지우고 turtle의 상태와 위치를 원래 기본값으로 재설정한다.|\n", "|turtle.screensize(w,h)|캔버스의 폭과 높이를 w와 h로 설정한다.|\n", "|turtle.hideturtle()|turtle을 보이지 않게 만든다.|\n", "|turtle.showturtle()|turtle을 보이게 만든다.|\n", "|turtle.isvisible()|turtle이 보이면 True를 반환한다.|\n", "|turtle.write(s,font=(\"Arial\",8,\"normal\"))|현재 turtle의 위치에 문자열 s를 쓴다. 폰트는 폰트명, 폰트크기, 폰트유형의 세 값으로 구성된다.|" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3) 연습문제" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- (1) 다음 사항을 읽고 요구하는 프로그램을 작성하시오.\n", " * 정다각형은 모든 변의 길이와 내각의 크기가 같은 $n$개의 변으로 이루어진 다각형이다 (즉, 다각형이 등변이고 등각이다). \n", " * 한변의 길이가 $s$일 때 정다각형의 넓이를 계산하는 공식은 다음과 같다.\n", " * $정다각형의 넓이 = (n \\times s^2) / (4 \\times tan(\\pi / n))$\n", " * 사용자로 부터 정다각형의 변의 개수와 변의 길이를 입력받고 정다각형의 넓이를 출력하는 프로그램을 작성하시오.\n", " * 출력예는 다음과 같다.\n", " \n", " [출력예]\n", " ```\n", " 변의 개수를 입력하세요: 5 \n", " 변의 길이를 입력하세요: 6.5\n", " 다각형의 넓이는 73.69017017488385 입니다.\n", " ```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- (2) 다음 사항을 읽고 요구하는 프로그램을 작성하시오.\n", " * 사용자로 부터 ASCII 코드 (0부터 127 사이의 정수)를 입력받는다. \n", " * 입력받은 코드에 대한 문자를 출력하는 프로그램을 작성하시오.\n", " * 출력예는 다음과 같다.\n", " \n", " [출력예]\n", " ```\n", " ASCII코드를 입력하세요: 69 \n", " 문자는 E 입니다.\n", " ```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- (3) 다음 프로그램을 분석해보고, 어떤 목적의 프로그램인지 파악해보시오. 또한, assert 예약어가 무엇인지 Googling 하여 알아보시오." ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import math\n", "\n", "def distance( x0, y0, x1, y1 ):\n", " \"\"\"( x0, y0 )와 ( x1, y1 ) 사이의 거리를 계산한다.\"\"\"\n", " return math.sqrt( (x1-x0) ** 2 + (y1-y0) ** 2 )\n", "\n", "def close( left, right ):\n", " \"\"\"두 부동소수점 값이 근사한지 테스트 한다.\"\"\"\n", " return abs( left - right ) < 1.0e-6\n", "\n", "def test_distance():\n", " \"\"\"distance 함수가 올바르게 동작하는지 테스트 한다.\"\"\"\n", " assert close( distance( 1.0, 0.0, 1.0, 0.0 ), 0.0 ), '동일 지점 실패'\n", " assert close( distance( 0.0, 0.0, 1.0, 0.0 ), 1.0 ), '단위 거리 실패'\n", "\n", "test_distance() " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- (4) Python 터틀로 다음 그림을 그려보시오." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![image](http://openbookproject.net/thinkcs/python/english3e/_images/tess07.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. E-learning 1, 2 보충 자료" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1) 현재 이름 공간에 있는 이름 리스트 출력" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- dir() 내장 함수 사용\n", " - 리턴형: 리스트 \n", " \n", "- 아래 리스트 중 python 기본 이름\n", " - \\_\\_builtins\\_\\_\n", " - \\_\\_doc\\_\\_\n", " - \\_\\_name\\_\\_\n", " \n", "- 나머지는 ipython이 자체적으로 생성한 이름들" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 단순 이름만 출력: dir()\n", " - 리턴형: 리스트" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['In',\n", " 'Out',\n", " '_',\n", " '__',\n", " '___',\n", " '__builtin__',\n", " '__builtins__',\n", " '__doc__',\n", " '__name__',\n", " '_dh',\n", " '_i',\n", " '_i1',\n", " '_ih',\n", " '_ii',\n", " '_iii',\n", " '_oh',\n", " '_sh',\n", " 'exit',\n", " 'get_ipython',\n", " 'quit']" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2) 특정 객체가 지니고 있는 이름 리스트 출력" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']\n" ] } ], "source": [ "a = 10\n", "print dir(a)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__IPYTHON__', '__IPYTHON__active', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'dreload', 'enumerate', 'eval', 'execfile', 'file', 'filter', 'float', 'format', 'frozenset', 'get_ipython', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']\n" ] } ], "source": [ "print dir(__builtin__)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3) 파이썬 버전 및 모듈들이 존재할 수 있는 패스 알아보기" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2.7.9 | 64-bit | (default, Jun 30 2015, 22:40:22) \n", "[GCC 4.1.2 20080704 (Red Hat 4.1.2-55)]\n", "\n", "['', '/home/goslim/Canopy/appdata/canopy-1.5.5.3123.rh5-x86_64/lib/python27.zip', '/home/goslim/Canopy/appdata/canopy-1.5.5.3123.rh5-x86_64/lib/python2.7', '/home/goslim/Canopy/appdata/canopy-1.5.5.3123.rh5-x86_64/lib/python2.7/plat-linux2', '/home/goslim/Canopy/appdata/canopy-1.5.5.3123.rh5-x86_64/lib/python2.7/lib-tk', '/home/goslim/Canopy/appdata/canopy-1.5.5.3123.rh5-x86_64/lib/python2.7/lib-old', '/home/goslim/Canopy/appdata/canopy-1.5.5.3123.rh5-x86_64/lib/python2.7/lib-dynload', '/home/goslim/Enthought/Canopy_64bit/User/lib/python2.7/site-packages', '/home/goslim/Canopy/appdata/canopy-1.5.5.3123.rh5-x86_64/lib/python2.7/site-packages', '/home/goslim/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/IPython/extensions']\n" ] } ], "source": [ "import sys\n", "print sys.version\n", "print\n", "print sys.path" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_home', '_mercurial', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'exitfunc', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'hexversion', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'ps3', 'py3kwarning', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions']\n" ] } ], "source": [ "print dir(sys)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4) 연습문제" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 다음은 math 모듈을 가져오는 코딩이다. math 모듈을 가져온 후 math 모듈에 정의된 함수를 이용하여 -4.3 값을 반올림한 후 절대값을 계산하여 출력하는 코딩을 한 줄로 완성하라." ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import math" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 다음은 두 점의 좌표 (x1, y1), (x2, y2)를 나타내는 변수 값들이다. math 모듈에 정의된 함수를 이용하여 이 두 점 사이의 거리를 계산하여 출력하는 코딩을 한 줄로 완성하라. " ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": true }, "outputs": [], "source": [ "x1 = 10\n", "y1 = 20\n", "x2 = 30\n", "y2 = 40" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "anaconda-cloud": {}, "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.1" } }, "nbformat": 4, "nbformat_minor": 1 }