SlideShare a Scribd company logo
앞서가는 생명정보분석을 위한
파이썬 프로그래밍

Hyungyong Kim

E-mail_hygkim@insilicogen.com
R&D Center,
Insilicogen, Inc.
파이썬 설치




 • 강의 전 아래 웹사이트에서 파이썬 프로그램을 다운
   로드 받아 설치해주세요.

 • http://www.python.org

 • Download “Python 2.7.3 Windows Installer”

 • 설치 후, ;C:Python27 를 PATH 환경변수에 추가
강사소개




 •   아주대학교 생물공학과 93
 •   생물정보훈련과정 1기 (2000년)
 •   ㈜바이오인포메틱스
 •   국립축산과학원 생물정보실
 •   숭실대학교 생명정보학과
 •   ㈜인실리코젠

 •   LabKM, KinMatch, Ontle
 •   6.25전사자 유전자정보 검색시스템
 •   실종아동등찾기 DNA정보 검색시스템
 •   가축유전자원종합관리시스템
                              http://biohackers.net
                              http://yong27.biohackers.net
                              http://twitter.com/yong27
앞서가는 생물정보 분석




 • 머리속의 아이디어를 빠르게 구현
 • Battery included. 이미 만들어진 라이브러리 이용
 • Prototype  Product
교육 구성




 • 기본문법                                 • 기본 실습문제
   –   Python introduction               – 구구단 함수
   –   Data type                         – 이차방정식 근의 공식
   –   Control flow                      – 단어빈도수 계산
   –   Function, Module, Package
   –   String formatting
 • 객체지향과 고급기능                           • 객체지향 문제
   –   Exception and Test                – FASTA 서열 다루기
   –   Class
   –   Decorator, Iterator, Generator
   –   Standard libraries
INTRODUCTION
“미래는 창조적이지 않은 모든 일들을 기술이 대체할 것이다.”
Computer language




  •   Information is a sequence (order)
  •   How can we manage it?
  •   Computer language is for it by mimic human’s language
  •   History
      –    Machine language
      –    Assembly
      –    Compiled language (C,…)
      –    Interpreter language
          (Java, Python,…)
Operating System




  • Unix (linux)
  • MS-Windows
  • Mac OS X

  • Python runs everywhere
What is Python?




  •   1991’s Guido Van Rossum
  •   Free and Open source
  •   For easy language
  •   Object oriented scripting
  •   Dynamic typing
  •   Interpreter
  •   Glue language
Why Python?




 •   Easy object oriented
 •   Easy to learn
 •   Prototyping
 •   Battery included
 •   Portable
 •   Extensible
 •   Powerful internal data structure
Indentation
Python applications




  •   아나콘다
  •   구글의 3대 언어가운데 하나
  •   NASA
  •   Biopython
  •   Django – Pinterest, Instagram
Python applications




  •   Web programming – Django, Turbo gears
  •   Network programming – Twisted
  •   GUI – wxPython, PyQt
  •   Game - pygame
  •   Database – Oracle, MySQL, PostgreSQL, sqlite
  •   Scientific and numeric – Numpy, Scipy
Python version




  • 3.2.3
  • 2.7.3
  • 2.6
  • 2.5
  • 2.4
  …
  • 1.5
Python implementation




  •   Cpython (C)
  •   Pypy (python)
  •   Jython (java)
  •   Parrot (perl)
  •   IronPython (.NET)
DATA TYPE
Variables




  • 첫문자가 “_” 혹은 영문자, 두번째 문자부터는 숫자도 가능, 대
    소문자 구분
  • 예약어는 안됨 (import keyword)
  • 내장함수 이름은 피한다.

  • “a = 1”
      – 파이썬에서는 모든 것이 객체
      – 객체에 이름부여
Python internal data types




  • Numeric types
      – Integer, Long, Float, Decimal, Complex
  • Sequence types
      – String, Unicode, List, Tuple
  • Collection types
      – Dictionary, Set
  • Etc
      – Boolean
Numeric types




  •   int, long, float, complex
  •   +, -, *, /, //, %, **
  •   Builtin functions : abs, divmod, pow
  •   For advanced calculation, use import math
Integer and Long




  • Integer and long literal
      –   ~L : Long
      –   0b~ : 2진수(bin) : 0b101  5
      –   0o~ : 8진수(oct) : 011  9
      –   0x~ 16진수(hex) : 0xa  10
  • Long merged to int in python3
Float




  • 3.14 10. .001 1e100 3.14e-10 0e0

  • Builtin functions : round
  • Float is not precise number
  • Use Decimal but it is slow
Complex




 • 3.14j 10.j 1e100j 3+4J

 • Method : conjugate, real, imag
Method?




 • In Python, all is object
 • Object has attributes. Use “.” for access
 • Some attribute is method. Use “()” for call

 •   a = 27
 •   dir(a)
 •   help(a)
 •   a.real
 •   a.imag
 •   a.conjugate()
Sequence types




  • Immutable : String, Unicode, Tuple
  • Mutable : List
Sequencing indexing/slicing


                                                  -4   -3    -2    -1


  MyStr =        HEL LO                   WO R L D !
             0   1   2   3    4   5   6   7   8    9    10    11        12



   MyStr[1]  “E”                         MyStr[3:5]  “LO”
   MyStr[6]  “W”                         MyStr[8:-1]  “RLD”
   MyStr[-1]  “!”                        MyStr[9:]  “LD!”
                                          MyStr[:4]  “HELL”
                                          MyStr[:]  “HELLO WORLD!”
String




  • It is a byte stream
  • Methods : capitalize, center, count, endswith, startswith, find,
    index, join, strip, split, zfill
  • Bach slash is special
         – n : ASCII linefeed
         – t : ASCII horizontal tab
  • String literals
         – r~ : raw string (back slash is not escaping)
         – u~ : unicode
Tuple




  • Immutable sequence of anything
  • Use “( )”
List



  • Mutable sequence of anything, Use “[ ]”
Set




  • Unordered collection of distinct hashable objects
  • Mutability
      – Mutable : set (add, remove)
      – Immutable : frozenset
  • Methods : union(|), intersection(&), difference(-),
    symmetric_difference(^)
Dictionary




  • Mapping object maps hashable values to arbitrary objects.
  • Mutable
  • Usages
      –   d = { key : value }
      –   d[key] = value
      –   key in d
      –   d.keys(), d.values(), d.items()
      –   d.update(annother_d)
Bool




  • Boolean type
  • True or False
  • All python objects has boolean value
CONTROL FLOW
Scope



  • 괄호 {} 대신 들여쓰기로 현
    재 범위 규정
  • 들여쓰기가 끝나면 해당
    Scope 가 끝남을 의미
  • 아무것도 안할 때는 pass
if statement




  • bool() 함수로 평가하여, True, False 에 따라 분기
  • elif, else 는 옵션
if statement


  • Operator : >, <, >=, <=, !=, ==
  • When string, alphabet order
  • When sequence type, from first element
  • When other types, number < dict < list < string < tuple
  • hasattr
  • belong check uses “in” statement : when dict, checks keys
    default
  • Same object check uses “is” statement
  • None, 0, 0.0, “”, [], (), {} is False
Logical calculation




  • not
  • and, or
      –   True and True  True
      –   True and False  False
      –   False and False  False
      –   False or False  False
      –   True or False  True
      –   It returns that value. So can use one line if statement
           • if a: return b else: return c  a and b or c
  • all(), any()
for statement



  • Repeat elements in sequence types data
for statement




  • When dict
      – keys(), values(), items()
      – Default is keys()
  • When list
      – Use [:] copy when self alteration
The range() function




                       • range([start,], stop[,
                         step])  list of
                         integers
구구단 출력




    print 2, “*”, 1, “=“, 2 * 1
The enumerate() function




  • enumerate(sequence[, start=0])
break and continue statement


  • break : breaks out the loop
  • continue : next iteration of the loop
  • else : end without break or continue
while statement




  • Repeat while an
    expression is true
  • Used in break, continue,
    else
Fibonacci series




  • 어떤 사람이 벽으로 둘러싸인 어떤 곳에다 토끼 암수 한 쌍
    을 집어 넣었다. 매달 한 쌍의 토끼가 태어나고 또 그 신생
    토끼의 쌍이 두 달째부터 새끼를 낳을 수 있다면, 1년 뒤 원
    래의 한 쌍으로부터 얼마나 많은 쌍의 토끼가 태어날까?
Sort




  •    L.sort(cmp=None, key=None, reverse=False)
  •    Builtin functions: sorted, reversed
  •    cmp(x, y)  -1, 0, 1
  •    key  compare function
  •    Dictionary sorting (by key, by value)
List comprehension




  • L = [ k*k for k in range(10) if k > 0]

  • L=[]
  • for k in range:
  •    if k > 0:
  •        L.append(k*k)
FUNCTION MODULE PACKAGE
Functions




            2,4

                                  def pow(a, b):
                  Function name
                                    result = a ** b
                    : pow
                                    return result
            2 ** 4



                          16
Quadratic equation


      23x^2 + 43.2x + 34 = 0

                           2
                     b   b     4ac
               x
                         2a
Quadratic equation




   import cmath
   def quadratic_equation(a, b, c):
     in_sqrt = cmath.sqrt(b*b – 4*a*c)
     x1 = (-b + in_sqrt) / (2.0*a)
     x2 = (-b – in_sqrt) / (2.0*a)
     return x1, x2

   print quadratic_equation(23, 43.2, 34)
   ((-0.9391304347+0.7722013312j), (-0.9391304347-
      0.7722013312j))
Defining Functions
Defining Functions
Globals and locals




   h=5

   def f():
     a = h + 10      # Can refer name but not change
     print a

   def f():
      global h
      h = h + 10
      print h
   print h
Nested function




  Search names from inside to outside

  x=2
  def F():
    x=1
    def G():
       print x
    G()
  F()
Arbitrary argument lists




  def write_multiple_items(file, separator, *args):
    file.write(separator.join(args))

  >>> # Unpacking argument lists
  >>> range(3,6)
  [3, 4, 5]
  >>> args = [3, 6]
  >>> range(*args)
  [3, 4, 5]
Keyword arguments
Arbitrary keyword argument




   def cheeseshop(kind, *args, **kwargs):
     assert type(args) == list
     assert type(kwargs) == dict

   >>> # Unpacking argument dict
   >>> mydict = {‘client’:’michael’, ‘sketch’:’cap’}
   >>> mylist = [‘b’, ‘c’]
   >>> cheeseshop(‘a’, ‘b’, ‘c’, client=‘michael’, sketch=‘cap’)
   >>> cheeseshop(‘a’, *mylist, **mydict)
Various ways for dict




  •   {‘one’:2, ‘two’:3)
  •   dict(one=2, two=3)
  •   dict({‘one’:2, ‘two’:3})
  •   dict(zip((‘one’, ‘two’), (2, 3)))
  •   dict([[‘two’, 3], [‘one’, 2]])
Python functional programming




  •   LISP, Heskel
  •   Function is an object
  •   Recursion
  •   Expression evaluation instead of statement
  •   It can be used in control flow
  •   In Python: map, reduce, filter, lambda, list comprehension
      (,iterator, generator)
Python functional programming




   >>> def sqr(x): return x*x
   …
   >>> def cube(x): return x*x*x
   …
   >>> sqr
   <function sqr at …>
   >>> a = [sqr, cube]
   >>> a[0](2)
   >>> def compose(f, g): return f(g(x))
   >>> compose(sqr, cube, 2)
   64
lambda, map, reduce, filter




   >>> f = lambda x: x+4
   >>> f(3)
   7
   >>> a = [‘1’, ‘2’, ‘3’]
   >>> map(int, a)
   >>> [1, 2, 3]
   >>> reduce(lambda x, y: x+y, [1,2,3,4,5])
   >>> ((((1+2)+3)+4)+5)
   >>> filter(lambda x: x%2, range(10))
   [1, 3, 5, 7, 9]
Module




   A file containing Python definitions and statements.
   The file name  module name (.py)
   In fib.py, fib, fib2 functions existed,
    ◦ from fib import fib, fib2
    ◦ fib(3)
    or
    ◦ import fib
    ◦ fib.fib2(3)
    or
    ◦ from fib import *
    ◦ fib(3)
import path




  • That file is in current directory or PYTHONPATH
    environmental variable
  • Or
      import sys
      sys.path.append(‘/mydirectory’)
Module




   Byte compile for Virtual Machine
    ◦ import statement search .pyc first.
    ◦ If .py is new, recompile it
    ◦ If use –O option (optimization), it makes .pyo
   For reload, use reload(module)
   If module was executed program mode, __name__ is
    ‘__main__’ but module importing, __name__ is module name
   So, for scripting (not for importing), use
         if __name__ == “__main__”:
             fib(3)
Packages




 • A way of structuring python module namespace by using
   “dotted module names”
Packages




  import sound.effects.echo
  sound.effects.echo()…

  Or

  from sound.effects import echo
  echo()…

  Or

  from sound.effects import echo as myecho
  myecho()…
STRING FORMATING AND FILE IO
Functions for string



  •   str – 비형식적 문자열로 변환
  •   repr – 형식적 문자열로 변환
  •   eval – 문자열을 실행 (expression, 식)
  •   exec – 문자열을 실행 (statement, 문)
      >>> s = 'Hello, world'      >>> s1 = repr([1,2,3])
      >>> str(s)                  >>> s1
      'Hello, world'              „[1, 2, 3]'
      >>> repr(s)                 >>> eval(s1)
      "'Hello, world'"            [1, 2, 3]
      >>>                         >>>
      >>> str(0.1)                >>> a = 1
      '0.1'                       >>> a = eval(„a + 4‟)
      >>> repr(0.1)               >>> a
      '0.10000000000000001'       5
      >>>                         >>> exec „a = a + 4‟
                                  >>> a
                                  9
String formatting (old style)



   >>> template = "My name is %s and I have %i won"
   >>> template % ("yong", 1000)
   'My name is yong and I have 1000 won'
   >>>
   >>> template = "My name is %(name)s and I have %(money)i won"
   >>> template % {'name':'yong', 'money':1000}
   'My name is yong and I have 1000 won'
   >>>
   >>> name = 'yong'
   >>> money = 1000
   >>> template % locals()
   'My name is yong and I have 1000 won'
   >>>
   >>> import math
   >>> print 'The value of PI is approximately %5.3f.' % math.pi
   The value of PI is approximately 3.142.
   >>>
String formatting operation




  • Similar with sprintf() in C
String formatting (new style) 1



   >>> template = "My name is {0} and I have {1} won"
   >>> template.format("yong", 1000)
   'My name is yong and I have 1000 won'
   >>>
   >>> template = "My name is {name} and I have {money} won"
   >>> template.format(name=„yong', money=1000}
   'My name is yong and I have 1000 won'
   >>>
   >>> print 'The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
   ...                                                     other='Georg')
   The story of Bill, Manfred, and Georg.
   >>>
   >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
   >>> for name, phone in table.items():
   ...    print '{0:10} ==> {1:10d}'.format(name, phone)
   ...
   Jack      ==>       4098
   Dcab      ==>      7678
   Sjoerd ==>         4127
String formatting (new style) 2



   "First, thou shalt count to {0}" # References first positional argument
   "My quest is {name}"             # References keyword argument 'name'
   "Weight in tons {0.weight}"      # 'weight' attribute of first positional arg
   "Units destroyed: {players[0]}" # First element of keyword argument
                                     'players'.


   "Harold's a clever {0!s}"         # Calls str() on the argument first
   "Bring out the holy {name!r}"     # Calls repr() on the argument first


   "A man with two {0:{1}}".format("noses", 10)
Reading and Writing Files



  >>> f = open(„/tmp/workfile‟, „w‟)
  >>> print f
  <open file „/tmp/workfile‟, mode „w‟ at 80a0960>

  • mode : ‘r’, ‘w’, ‘a’, ‘r+’, ‘b’, ‘rb’, ‘wb’
  • Method : read, readline, readlines, write
  >>> f.read()                                >>> f.readlines()
  'This is the entire file.n'                ['This is the first line of the file.n', 'Second
  >>> f.read()                                line of the filen']
  '„                                          >>>
  >>> f.readline()                            >>> for line in f:
  'This is the first line of the file.n'                 print line,
  >>> f.readline()                            This is the first line of the file. Second line
  'Second line of the filen'                 of the file
  >>> f.readline()                            >>>
  ''                                          >>> f.write(str(43))
Position in the file




  • f.tell() : current position
  • F.seek(offset, from_what) : go there position
       – from_what : 0 start, 1 current, 2 end

      >>> f = open('/tmp/workfile', 'r+')
      >>> f.write('0123456789abcdef')
      >>> f.seek(5) # Go to the 6th byte in the file
      >>> f.read(1)
      '5'
      >>> f.seek(-3, 2) # Go to the 3rd byte before the end
      >>> f.read(1)
      'd'
File close




  • f.close() : close it and free up any system resource
  • “with” keyword when free up

      >>> f.close()
      >>> f.read()
      Traceback (most recent call last):
       File "<stdin>", line 1, in ?
      ValueError: I/O operation on closed file

      >>> with open('/tmp/workfile', 'r') as f:
      ...      read_data = f.read()
      >>> f.closed
      True
Standard IO



  • stdin, stdout, stderr
  • Command line pipe “>”, “2>”, “<“, “|”
    def work(input_file, output_file):
      output_file.write("<")
      output_file.write(input_file.read())
      output_file.write(">")

    work(open('a.txt'), open('b.txt', 'w'))

    import sys
    work(sys.stdin, sys.stdout)
    -----
    python a.py < a.txt > b.txt


  • Different with sys.argv
StringIO




  • Virtual file on memory

    from cStringIO import StringIO

    handle = StringIO("""
    > test fasta
    AGTCAGTC
    AGTCCCCC
    """)

    for line in handle:
       print line
Character encoding




  • 문자들의 집합(Character set)을 부호화하는것
      –   ASCII : 7비트, 인코딩
      –   ISO-Latin1(ISO-8859-1) : 8비트, 대부분의 서구유럽언어 표시
      –   한글조합형
      –   한글완성형  EUC-KR  CP949 : 2바이트
  • 인코딩간 호환문제
  • Unicode
Unicode




  • 전세계의 모든 문자를 표시하기 위한 체계
  • 목적 : 모든 인코딩 방법을 유니코드로 교체
  • 인코딩
     – UTF-7
     – UTF-8 : 가변문자열 (2바이트 혹은 4바이트)
     – UTF-16
Unicode in Python




• ‘a’  str
• u‘a’  unicode
• ‘a’ + u‘bc’  u‘abc’

• Unicode  Str
• encode/decode
• Character set
Unicode in Python 2




  • Python default encoding : ASCII  UTF-8
      – Used in unicode file IO
  • Source code encoding : ASCII
      – # -*- coding:utf-8 -*-
  • 한글이 깨진다면,
      – 저장된 정보의 인코딩 확인
      – 디스플레이 환경 (터미널, 에디터, 웹브라우저 등)
Hangul examples




                                              hangul.py 필요
        >>> import hangul
        >>> haveJongsung = lambda u: bool(hangul.split(u[-1])[-1])
        >>> haveJongsung(u'자음'))
        True
        >>> haveJongsung(u„자'))
        False
Excersize


  임의의 텍스트파일내 단어의 출현 빈도를 조사하여 가장 많
  이 출현한 단어부터 정렬하여 출력하는 프로그램 (특수기호
  제외, 소문자로 통일)

  $ python word_frequency.py < input.txt
  32 the
  28 of
  17 boy
  …
Excersize


  임의의 FASTA 형식의 파일에 저장된 DNA 서열을 읽어 GC
  함량을 계산하시오 (single FASTA format)

  $ python gc_content.py < input.fasta
  0.55
Excersize


  임의의 FASTA 형식의 파일에 저장된 DNA 서열을 읽어
  Reverse complement 서열을 출력하시오 (Single FASTA)

  $ python reverse_complement.py < input.fasta
  > seq1 reverse complement
  AGTCAAGGCCAAGTCCAA
  AGCAGCAGGAGCCAAGGT
EXCEPTION AND TEST
Exception


 • Errors detected during execution
Built-in Exceptions


• Used by class inheritance

• BaseException
   –   SystemExit
   –   KeyboardInterrupt
   –   GeneratorExit
   –   Exception
Handling Exceptions




  • By default, when exception raised, program stopped and
    show error message
  • try/except/else/finally statement

   try:
      statements… #1
   except (exception types):
      statements… #2
   else:
      statements… #3
   finally:
      statements… #4
Handling Exceptions example
Handling Exceptions example
Handling Exceptions example



def dosomething():
  a = 1/0

try:
   dosomething()
except ArithmeticError:
   print „Exception occurred‟
Raising Exceptions




  • “raise” statement allows the programmer to force a specified
    exception to occur.
User-defined Exceptions




  • Programs may name their own exceptions by creating a new
    exception class
Assert statement




  • Usually, used when debugging
      a = 30
      margin = 2 * 0.2
      assert margin > 10, „not enough margin %s‟ % margin




      if not margin > 10:
          raise AssertionException(„not enough margin %s‟ % margin)
Unit test 란?




  • 프로그램을 작은 단위로 쪼개서 그 단위를 테스트하는 전통적인 프로그래
    밍 테스팅 방법중의 하나

  • 왜 필요한가?

  • Regression testing 개념
      – 인공적인 상황을 가정하고, 테스트모듈이 그 상황을 이용하여, 결과값을 계산한
        다. 이때 기대되는 값과, 계산 값이 같은가를 확인한다.
      – 프로그램이 퇴행하지 않도록 계속적으로 검사한다.
      – 프로그램이 수정되는 것 뿐만 아니라, 플랫폼이나 주변 환경 등의 요소의 변화
        에 의한 퇴행도 검사한다.




                                                bioxp
Test Driven Development




  •   테스트가 주도하는 프로그래밍
  •   기본 사이클
      –   Write a test
      –   Make it compile, run it to see it fails
      –   Make it run
      –   Remove duplication




                                                    bioxp
TDD의 장점




 •   테스트에는 실제 코드를 어떻게 사용하는지에 대해 작동하는 설명이 들어있다. (인
     터페이스가 정의된다.)
 •   따로 테스트를 할 필요가 없다.
 •   코드 수정 시 기존의 테스트 코드를 통과하는지 체크되기 때문에 통합적인 테스트
     가 유지된다.
 •   테스트가 용이한 코드가 유지보수관리가 용이하다.
 •   프로그램이 잘못되었는지를 "빨리" 알 수 있다(혹은 그럴 확률이 높다). (Fail early,
     often)
 •   어떤 기능을 구현할 때, 어떻게 사용할지를 먼저 생각하도록 이끄는 역할을 한다.
     (Programming by intention)
 •   오랜 시간이 지난 후에 다시 그 코드를 개선해야 할 일이 생길 때(혹은 어쨌던 봐야
     할 일이 있을 때), 빨리 접근할 수 있도록 도와준다. (Documentation)




                                                        bioxp
CLASS
Object Oriented




  • Programming paradigms
      – Procedural programming
      – Functional programming
      – Object oriented programming
  • It’s origin is the modeling of cell
  • Modeling of real world  Easy maintain
  • The keys : remove duplication, easy management
Example calculate average




      Name          Korean   English   Math   Science

      smith         80       69        70     88

      neo           92       66        80     72

      trinity       82       73        91     90

      oracle        80       42        100    92
Procedural example




   smith_korean = 80
   smith_english = 69
   smith_math = 70
   smith_science = 88

   neo_korean = 92
   neo_english = 66
   neo_math = 80
   neo_science = 88

   smith_average = (smith_korean + smith_english
                 + smith_math + smith_science) / 4.0
   neo_average = (neo_korean + neo_english
                 + neo_math + neo_science) / 4.0
Functional example



   def average(alist):
     return sum(alist) / float(len(alist))

   smith = {
     'korean': 80,
     'english': 69,
     'math': 70,
     'science': 88,
     }
   neo = {
     'korean': 92,
     'english': 66,
     'math': 80,
     'science': 88,
     }

   smith_average = average(smith.values())
   neo_average = average(neo.values())
Object oriented example



   class Score:
      def __init__(self, korea, english, math, science):
        self.korea = korea
        self.english = english
        self.math = math
        self.science = science
      def get_average(self):
        return (self.korea + self.english + self.math
                + self.science) / 4.0

   smith_score = Score(80, 69, 70, 88)
   smith_average = smith_score.get_average()
   neo_score = Score(92, 66, 80, 88)
   neo_average = neo_score.get_average()
Class statement




  • Collection of variables and functions
  • It is a kind of name space

  class Person:
     name = ‘yong’
     gender = ‘male’
     def get_age(self):
       return 27

  Person.name, Person.get_age()
Instance(object) and Class

   smith_score = Score(80, 69, 70, 88)


       object = Class()

        붕어빵          붕어빵틀
Class Person:                클래스 변수
        count = 0
        def __init__(self, name, gender):
생성자
          self.name = name                   인스턴스 변수
          self.gender = gender
          Person.count += 1                    메쏘드
                                            (인스턴스 함수)
        def set_age(self, age):
          self.age = age

      yong = Person(‘yong’, ‘male’)
      yong.set_age(27)
객체


                            메쏘드 호출
Constructor, Destructor



    • Constructor(생성자) : 객체가 만들어질 때 최초 수행되는
      함수

     class Person:
        count = 0
        def __init__(self, name, gender):
          self.name = name
          self.gender = gender
          Person.count += 1
        def __del__(self):
          Person.count -= 1
Operator overloading




  •   __add__(self, other) : +
                                 Class MyString:
  •   __sub__(self, other) : -     def __init__(self, str):
  •   __mul__(self, other) : *       self.str = str
                                   def __div__(self, sep):
  •   __div__(self, other) : /       return self.str.split(sep)

  •   __mod__(self, other) : %   >>> m = MyString(“abcdef”)
  •   __and__(self, other) : &   >>> print m / “b”
                                 [“a”, “cdef”]
  •   __or__(self, other) : |
Inheritance



    • Is-a relationship. “Man is a person”

     class Man(Person):
        def __init__(self, name):
          Person.__init__(self, name, „male‟)

     class Woman(Person):
        def __init__(self, name):
          Person.__init__(self, name, „female‟)

     yong = Man(„yong‟)
     yong.gender, yong.set_age(27)
Multiple Inheritance



     class Singer:
        def song(self):
          print “Oh my love~”

     class ManSinger(Man, Singer):
        def __init__(self, name):
          Man.__init__(self, name)

     yong = ManSinger(„yong‟)
     yong.song()
Subclassing


    class MyList(list):
       def __sub__(self, other):
         L = self[:]
         for x in other:
            if x in L:
                L.remove(x)
         return L

    >>> L = MyList([1,2,3,‟spam‟,4,5])
    >>> L = L – [„spam‟]
    >>> print L
    [1, 2, 3, 4, 5]
Polymorphism


    class Animal:
       def cry(self):
         print „…‟

    class Dog(Animal):
       def cry(self):
          print „멍멍‟

    class Duck(Animal):
       def cry(self):
         print “꽥꽥”

    for each in (Animal(), Dog(), Duck()):
       each.cry()
Composition



   • has-a relationship.
     class Set(list):
        def union(self, A):
          result = self[:]
          for x in A:
             if x not in result:
                 result.append(x)
          return Set(res)

     A = MySet([1,2,3])
     B = MySet([3,4,5])
     print A.union(B)
Encapsulation



   • Python do not support complete private
   • “from module import *” do not import name “_” starting


     class Encapsulation:
        z = 10
        __x = 1

     >>> Encapsulation.z
     >>> Encapsulation.__x
     >>> Encapsulation._Encapsulation__x
DECORATOR ITERATOR
GENERATOR
Decorator




  • 함수를 장식(decoration)하는 함수
                     def mydecorator(function):
    @A @B @C           def wrapper(*args, **kwargs):
    def f():              ## do something for decoration
      ….                  result = function(*args, **kwargs)
                          return result
    def f(): ….        return wrapper
    f = A(B(C(f)))
                     def require_int(function):
                       def wrapper(arg):
                          assert isinstance(arg, int)
                          return function(arg)
                       return wrapper

                     @require_int
                     def p1(arg):
                       print arg
Decorator




  • 인수를 가질 수도 있다.
      def mydecorator(arg1, arg2):
        def _mydecorator(function):
           def __mydecorator(*args, **kwargs):
              #do somethings for decoration
              result = function(*args, **kwargs)
              return result
           return __mydecorator
        return _mydecorator

      @mydecorator(1, 2)
      def f(arg):
        ….
Static method




  • 인스턴스를 생성하지 않고 클래스 이름으로 직접 호출할 수 있
    는 메쏘드
  • Instance method는 이처럼 호출하면 unbounded method 오류

    class D:
       def spam(x, y): # self 가 없다.
         print „static method‟, x, y
       spam = staticmethod(spam)

    D.spam(1, 2)                       class D:
                                          @staticmethod
                                          def spam(x, y):
                                            print „static method‟, x, y
Class method




  • 일반 메쏘드가 첫 인수(self)로 인스턴스 객체를 받는 것에 비해
    서, 클래스 메쏘드는 첫 인수로 클래스 객체를 받는다.



    class C:
       def spam(cls, y): # self 가 없다.
         print „class method‟, cls, y
       spam = classmethod(spam)

    >>> C.spam(5)                       class C:
    __main__.C 5                           @classmethod
                                           def spam(cls, y):
                                             print „class method‟, cls, y
get/set property




  • 멤버 값을 정의할 때 편하게 사용하기 위함
  • <예제> degree에 변수에 값을 저장하는데 360도 미만의 범위
    에서 정규화 하기
     class D(object):
        def __init__(self):
          self.__degree = 0
        def get_degree(self):
          return self.__degree
        def set_degree(self, d):
          self.__degree = d % 360
        degree = property(get_degree, set_degree)

     d = D()
     d.degree = 10    # set_degree call
     print d.degree   # get_degree call
Iterator




  • 순차적으로 참조는 하나, 인덱싱에 의한 순서적인 참조는 의미
    가 없는 경우  메모리 효율
  • iter() 내장함수로 만들며, next() 메쏘드를 갖는다.
  • 더 이상 넘겨줄 자료가 없으면 StopIteration 예외
     >>> I = iter([1,2,3])
     >>> I
     <iterator object at 0x1234556>
     >>> I.next()
     1
     >>> I.next()           >>> I.next() # 더이상 자료가 없으면 StopIteration
     2                      Traceback (most recent call last):
     >>> I.next()            File "<pyshell#71>", line 1, in ?
     3                        I.next()
                            StopIteration
Iterator on class




  • iter(s) 에 의해 s.__iter__() 가 호출되고 반복자 객체를 리턴한
    다.
  • 반복자 객체는 next() 메쏘드를 갖는다.

     class Seq:
        def __init__(self, fname):
          self.file = open(fname)
        def __iter__(self):
          return self
                                        >>> s = Seq(„readme.txt‟)
        def next(self):
                                        >>> for line in S:
          line = self.file.readline()
                                             print line,
          if not line:
              raise StopIteration
          return line
Generator




  • icon 이란 언어에서 영향을 받음
  • 기존의 함수 호출방식 – 인수들과 내부 변수들이 스택을 이용
    생성 소멸
  • 발생자란 (중단된 시점부터) 재실행 가능한 함수
  • 어떤 함수이든 yield 를 가지면 발생자 함수
  • 일종의 내맘대로 만드는 iterator
     def generate_int(n):
       while True:          def generate_int(n):
          yield n             while True:
          n += 1                 return n
                                 n += 1
Generator example




  • 피보나치 수열
    def fibonacci(a=1, b=1):
      while 1:
          yield a
          a, b = b, a+b

    t = fibonacci() # t는 반복자
    for i in range(10):
       print t.next(),
Generator example




  • 홀수 집합 만들기 (iterator 이용)
    class Odds:
       def __init__(self, limit=None):
         self.data = -1
         self.limit = limit
       def __iter__(self):
         return self
       def next(self):
         self.data += 2
         if self.limit and self.limit <= self.data:
             raise StopIteration
         return self.data

    >>> for k in Odds(20):
       print k,
    1 3 5 7 9 11 13 15 17 19
Generator example




  • 홀수 집합 만들기 (generator 이용)
    def odds(limit=None):
      k=1
      while not limit or limit >= k:
         yield k
         k += 2

    >>> for k in odds(20):
       print k,
    1 3 5 7 9 11 13 15 17 19
Generator expression




  • List comprehension
    >>> [k for k in range(100) if k % 5 == 0]
    [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]



  • Generator expression
    >>> (k for k in range(100) if k % 5 == 0) <generator object at 0x40190e4c>


  • Other example
    >>> sum(x for x in range(1, 20) if x % 2)
    >>> “, “.join(x for x in [“abc”, “def”] if x.startswith(“a”))
Iterator / generator 가 사용되는 곳




  •   iter()
  •   xrange()
  •   dict.iteritems(), dict.iterkeys(), dict.itervalues()
  •   file은 라인단위의 반복자를 지원한다.
  •   reversed()는 iterator를 받지 않는다.
Itertools module




  •    http://docs.python.org/library/itertools.html
  •    Infinite iterator: count, cycle, repeat
  •    Finite iterator: chain, groupby, ifilter,…
  •    Combinatoric iterator: product, permutations, combinations

      >>> text = “Hello world my world”
      >>> wd = dict( (k, len(list(v))) for k, v in groupby( sorted(text.split() ), lambda x:
      x.upper()) )
Excersize


  임의의 FASTA 형식의 파일에 저장된 DNA 서열을 읽어
  Reverse complement 서열을 출력하시오 (Multiple FASTA)

  $ python reverse_complement.py < input.fasta
  > seq1 reverse complement
  AGTCAAGGCCAAGTCCAA
  AGCAGCAGGAGCCAAGGT
  > seq2 reverse complement
  AGTCAAGGCCAAGTCCAA
  AGCAGCAGGAGCCAAGGT
STANDARD LIBRARIES
Library?




  • 특정 기능을 수행하기 위한 모듈 및 패키지  import 하여 사용
  • Python libraries
      – Built-in library : 파이썬 설치시 같이 설치됨
           • math, StringIO, random, unittest, re, itertools, decimal
           • os, sys, subprocess, glob, pickle, csv, datetime, Tkinter, …
      – 3rd party library : 따로 설치하여 사용해야함
           • wxPython, PythonWin, numpy, scipy, matplotlib, Biopython, PIL,
             BeautifulSoup…
os




 •   Miscellaneous operating system interfaces
 •   운영체제 의존적인 기능들을 일관적으로 사용
 •   os.name  ‘posix’, ‘nt’, ‘mac’, ‘os2’, ‘ce’, ‘java’, ‘riscos’
 •   os.environ  시스템 환경변수 사전
 •   os.chdir  현재 디렉토리 변경
 •   os.stat  파일의 속성
 •   os.walk  특정 디렉토리 하위 모든 파일들에 대한 일괄작업
 •   os.fork  프로세스 분기
sys




  •   System-specific parameters and functions
  •   시스템운영에 관련된 특정 상수값들과 함수
  •   sys.argv  명령행 인수
  •   sys.getdefaultencoding()  기본 인코딩
  •   sys.stdin, sys.stdout  표준입출력
Subprocess




 • Subprocess management
 • 다른 프로그램 이용하기
     – Shell pipeline
     – Process spawn
 • Popen, PIPE
glob




  • Unix style pathname pattern expansion
  • 와일드카드를 이용한 디렉토리내 파일 탐색
       –   ? : 아무런 문자 하나
       –   * : 0개 이상의 아무 문자
       –   [ ] : 사이에 나열된 문자 중 하나
       –   - : 일정 범위 a-z
pickle




  • Python object serialization
  • 파이썬 객체를 (파일에) 저장하기
  • dump() and load()
csv




 •    CSV File Reading and Writing
 •    표 데이터를 다루는 일반적인 방법
 •    CSV format : “,” 로 컬럼 구분. ‘ “” ’로 데이터 구분
 •    reader() and writer()
datetime




  • Basic date and time types
  • 날짜와 시각(시간)을 다루기
  • date, time, datetime, timedelta, tzinfo
Tkinter




  • Python interface to Tcl/Tk
  • Built-in GUI library, 운영체제 독립
wxPython




 •   Advanced GUI library for python
 •   http://www.wxpython.org
 •   3rd party GUI library, 운영체제 독립
 •   PythonWin 과 구분
numpy , scipy, matplotlib




  • numpy : 행렬, 벡터방식의 수치해석
  • scipy : 각종 과학연산용 라이브러리
  • matplotlib : matLab 프로그램의 영향을 받은 차트 라이브러리
PIL




  • Python Image Library
  • 그래픽이미지 변환 및 수정
BeautifulSoup




  • HTML, XML 문서 파싱 라이브러리
  • Invalide 형식도 적절하게 자동 해석
BioPython




  • 생물정보 관련 라이브러리
  • 생물서열 관리, 각종 문서형식 파싱, 주요 분석 알고리즘 탑재
www.insilicogen.com
E-mail km@insilicogen.com
Tel 031-278-0061
Fax 031-278-0062

More Related Content

What's hot

영상 데이터의 처리와 정보의 추출
영상 데이터의 처리와 정보의 추출영상 데이터의 처리와 정보의 추출
영상 데이터의 처리와 정보의 추출
동윤 이
 
(Lisp)
(Lisp)(Lisp)
파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영)
파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영) 파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영)
파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영)
Tae Young Lee
 
Python Programming: Function
Python Programming: FunctionPython Programming: Function
Python Programming: Function
Chan Shik Lim
 
TenforFlow Internals
TenforFlow InternalsTenforFlow Internals
TenforFlow Internals
Kiho Hong
 
자바8 람다 나머지 공개
자바8 람다 나머지 공개자바8 람다 나머지 공개
자바8 람다 나머지 공개
Sungchul Park
 
나에 첫번째 자바8 람다식 지앤선
나에 첫번째 자바8 람다식   지앤선나에 첫번째 자바8 람다식   지앤선
나에 첫번째 자바8 람다식 지앤선daewon jeong
 
파이썬+함수이해하기 20160229
파이썬+함수이해하기 20160229파이썬+함수이해하기 20160229
파이썬+함수이해하기 20160229
Yong Joon Moon
 
Jupyter notebook 이해하기
Jupyter notebook 이해하기 Jupyter notebook 이해하기
Jupyter notebook 이해하기
Yong Joon Moon
 
Collection framework
Collection frameworkCollection framework
Collection framework
ssuser34b989
 
Python on Android
Python on AndroidPython on Android
Python on Android
용 최
 
데이터 분석 4 - 나만의 배열 기반 LIST, MyArrayList를 만들어보자
데이터 분석 4 - 나만의 배열 기반 LIST, MyArrayList를 만들어보자데이터 분석 4 - 나만의 배열 기반 LIST, MyArrayList를 만들어보자
데이터 분석 4 - 나만의 배열 기반 LIST, MyArrayList를 만들어보자
Jaewook Byun
 
알고리즘과 자료구조
알고리즘과 자료구조알고리즘과 자료구조
알고리즘과 자료구조
영기 김
 
Swift3 generic
Swift3 genericSwift3 generic
Swift3 generic
Eunjoo Im
 
파이썬+Json+이해하기 20160301
파이썬+Json+이해하기 20160301파이썬+Json+이해하기 20160301
파이썬+Json+이해하기 20160301
Yong Joon Moon
 
Java 변수자료형
Java 변수자료형Java 변수자료형
Java 변수자료형
Hyosang Hong
 
파이썬2.7 기초 공부한 것 정리
파이썬2.7 기초 공부한 것 정리파이썬2.7 기초 공부한 것 정리
파이썬2.7 기초 공부한 것 정리
Booseol Shin
 

What's hot (19)

영상 데이터의 처리와 정보의 추출
영상 데이터의 처리와 정보의 추출영상 데이터의 처리와 정보의 추출
영상 데이터의 처리와 정보의 추출
 
(Lisp)
(Lisp)(Lisp)
(Lisp)
 
파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영)
파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영) 파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영)
파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영)
 
Python Programming: Function
Python Programming: FunctionPython Programming: Function
Python Programming: Function
 
TenforFlow Internals
TenforFlow InternalsTenforFlow Internals
TenforFlow Internals
 
자바8 람다 나머지 공개
자바8 람다 나머지 공개자바8 람다 나머지 공개
자바8 람다 나머지 공개
 
나에 첫번째 자바8 람다식 지앤선
나에 첫번째 자바8 람다식   지앤선나에 첫번째 자바8 람다식   지앤선
나에 첫번째 자바8 람다식 지앤선
 
파이썬+함수이해하기 20160229
파이썬+함수이해하기 20160229파이썬+함수이해하기 20160229
파이썬+함수이해하기 20160229
 
Jupyter notebook 이해하기
Jupyter notebook 이해하기 Jupyter notebook 이해하기
Jupyter notebook 이해하기
 
강의자료4
강의자료4강의자료4
강의자료4
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
Python on Android
Python on AndroidPython on Android
Python on Android
 
데이터 분석 4 - 나만의 배열 기반 LIST, MyArrayList를 만들어보자
데이터 분석 4 - 나만의 배열 기반 LIST, MyArrayList를 만들어보자데이터 분석 4 - 나만의 배열 기반 LIST, MyArrayList를 만들어보자
데이터 분석 4 - 나만의 배열 기반 LIST, MyArrayList를 만들어보자
 
알고리즘과 자료구조
알고리즘과 자료구조알고리즘과 자료구조
알고리즘과 자료구조
 
Swift3 generic
Swift3 genericSwift3 generic
Swift3 generic
 
파이썬+Json+이해하기 20160301
파이썬+Json+이해하기 20160301파이썬+Json+이해하기 20160301
파이썬+Json+이해하기 20160301
 
Scalability
ScalabilityScalability
Scalability
 
Java 변수자료형
Java 변수자료형Java 변수자료형
Java 변수자료형
 
파이썬2.7 기초 공부한 것 정리
파이썬2.7 기초 공부한 것 정리파이썬2.7 기초 공부한 것 정리
파이썬2.7 기초 공부한 것 정리
 

Viewers also liked

Python Programming: Data Structure
Python Programming: Data StructurePython Programming: Data Structure
Python Programming: Data Structure
Chan Shik Lim
 
Python Programming: Class and Object Oriented Programming
Python Programming: Class and Object Oriented ProgrammingPython Programming: Class and Object Oriented Programming
Python Programming: Class and Object Oriented Programming
Chan Shik Lim
 
H3 2011 모바일에서의 Location API 완전정복
H3 2011 모바일에서의 Location API 완전정복H3 2011 모바일에서의 Location API 완전정복
H3 2011 모바일에서의 Location API 완전정복KTH
 
『고성능 파이썬』 - 맛보기
『고성능 파이썬』 - 맛보기『고성능 파이썬』 - 맛보기
『고성능 파이썬』 - 맛보기
복연 이
 
H3 2011 파이썬으로 클라우드 하고 싶어요
H3 2011 파이썬으로 클라우드 하고 싶어요H3 2011 파이썬으로 클라우드 하고 싶어요
H3 2011 파이썬으로 클라우드 하고 싶어요KTH
 
Pycon2016 파이썬으로똑똑한주식투자 김대현
Pycon2016 파이썬으로똑똑한주식투자 김대현Pycon2016 파이썬으로똑똑한주식투자 김대현
Pycon2016 파이썬으로똑똑한주식투자 김대현
Daehyun (Damon) Kim
 
Object-oriented Programming in Python
Object-oriented Programming in PythonObject-oriented Programming in Python
Object-oriented Programming in Python
Juan-Manuel Gimeno
 
금융 데이터 이해와 분석 PyCon 2014
금융 데이터 이해와 분석 PyCon 2014금융 데이터 이해와 분석 PyCon 2014
금융 데이터 이해와 분석 PyCon 2014
Seung-June Lee
 
Python Programming: Tuning and Optimization
Python Programming: Tuning and OptimizationPython Programming: Tuning and Optimization
Python Programming: Tuning and Optimization
Chan Shik Lim
 

Viewers also liked (9)

Python Programming: Data Structure
Python Programming: Data StructurePython Programming: Data Structure
Python Programming: Data Structure
 
Python Programming: Class and Object Oriented Programming
Python Programming: Class and Object Oriented ProgrammingPython Programming: Class and Object Oriented Programming
Python Programming: Class and Object Oriented Programming
 
H3 2011 모바일에서의 Location API 완전정복
H3 2011 모바일에서의 Location API 완전정복H3 2011 모바일에서의 Location API 완전정복
H3 2011 모바일에서의 Location API 완전정복
 
『고성능 파이썬』 - 맛보기
『고성능 파이썬』 - 맛보기『고성능 파이썬』 - 맛보기
『고성능 파이썬』 - 맛보기
 
H3 2011 파이썬으로 클라우드 하고 싶어요
H3 2011 파이썬으로 클라우드 하고 싶어요H3 2011 파이썬으로 클라우드 하고 싶어요
H3 2011 파이썬으로 클라우드 하고 싶어요
 
Pycon2016 파이썬으로똑똑한주식투자 김대현
Pycon2016 파이썬으로똑똑한주식투자 김대현Pycon2016 파이썬으로똑똑한주식투자 김대현
Pycon2016 파이썬으로똑똑한주식투자 김대현
 
Object-oriented Programming in Python
Object-oriented Programming in PythonObject-oriented Programming in Python
Object-oriented Programming in Python
 
금융 데이터 이해와 분석 PyCon 2014
금융 데이터 이해와 분석 PyCon 2014금융 데이터 이해와 분석 PyCon 2014
금융 데이터 이해와 분석 PyCon 2014
 
Python Programming: Tuning and Optimization
Python Programming: Tuning and OptimizationPython Programming: Tuning and Optimization
Python Programming: Tuning and Optimization
 

Similar to Python programming for Bioinformatics

GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
Kyoungchan Lee
 
파이썬 데이터 분석 (18년)
파이썬 데이터 분석 (18년)파이썬 데이터 분석 (18년)
파이썬 데이터 분석 (18년)
SK(주) C&C - 강병호
 
[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기
Sang Heon Lee
 
Let's Go (golang)
Let's Go (golang)Let's Go (golang)
Let's Go (golang)
상욱 송
 
Python 스터디
Python 스터디Python 스터디
Python 스터디
sanghyuck Na
 
코딩테스트 합격자 되기 2주차 스터디 - 리스트_딕셔너리
코딩테스트 합격자 되기 2주차 스터디 - 리스트_딕셔너리코딩테스트 합격자 되기 2주차 스터디 - 리스트_딕셔너리
코딩테스트 합격자 되기 2주차 스터디 - 리스트_딕셔너리
ultrasuperrok
 
Scala, Scalability
Scala, ScalabilityScala, Scalability
Scala, Scalability
Dongwook Lee
 
[C++ Korea 2nd Seminar] C++17 Key Features Summary
[C++ Korea 2nd Seminar] C++17 Key Features Summary[C++ Korea 2nd Seminar] C++17 Key Features Summary
[C++ Korea 2nd Seminar] C++17 Key Features Summary
Chris Ohk
 
파이선 실전공략-1
파이선 실전공략-1파이선 실전공략-1
파이선 실전공략-1
Nomota Hiongun KIM
 
파이썬으로 익히는 딥러닝
파이썬으로 익히는 딥러닝파이썬으로 익히는 딥러닝
파이썬으로 익히는 딥러닝
SK(주) C&C - 강병호
 
Java Class File Format
Java Class File FormatJava Class File Format
Java Class File Format
Jongyoung Park
 
Swift2
Swift2Swift2
Swift2
HyungKuIm
 
I phone 2 release
I phone 2 releaseI phone 2 release
I phone 2 release
Jaehyeuk Oh
 
하스켈 프로그래밍 입문
하스켈 프로그래밍 입문하스켈 프로그래밍 입문
하스켈 프로그래밍 입문
Kwang Yul Seo
 
Python datatype
Python datatypePython datatype
Python datatype
건희 김
 
파이썬 언어 기초
파이썬 언어 기초파이썬 언어 기초
파이썬 언어 기초
beom kyun choi
 
eclipse에서 intelliJ IDEA로
eclipse에서 intelliJ IDEA로eclipse에서 intelliJ IDEA로
eclipse에서 intelliJ IDEA로
Juntai Park
 
불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14 불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14
명신 김
 
[A1]루비는 패셔니스타
[A1]루비는 패셔니스타[A1]루비는 패셔니스타
[A1]루비는 패셔니스타NAVER D2
 
Python
PythonPython

Similar to Python programming for Bioinformatics (20)

GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
 
파이썬 데이터 분석 (18년)
파이썬 데이터 분석 (18년)파이썬 데이터 분석 (18년)
파이썬 데이터 분석 (18년)
 
[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기
 
Let's Go (golang)
Let's Go (golang)Let's Go (golang)
Let's Go (golang)
 
Python 스터디
Python 스터디Python 스터디
Python 스터디
 
코딩테스트 합격자 되기 2주차 스터디 - 리스트_딕셔너리
코딩테스트 합격자 되기 2주차 스터디 - 리스트_딕셔너리코딩테스트 합격자 되기 2주차 스터디 - 리스트_딕셔너리
코딩테스트 합격자 되기 2주차 스터디 - 리스트_딕셔너리
 
Scala, Scalability
Scala, ScalabilityScala, Scalability
Scala, Scalability
 
[C++ Korea 2nd Seminar] C++17 Key Features Summary
[C++ Korea 2nd Seminar] C++17 Key Features Summary[C++ Korea 2nd Seminar] C++17 Key Features Summary
[C++ Korea 2nd Seminar] C++17 Key Features Summary
 
파이선 실전공략-1
파이선 실전공략-1파이선 실전공략-1
파이선 실전공략-1
 
파이썬으로 익히는 딥러닝
파이썬으로 익히는 딥러닝파이썬으로 익히는 딥러닝
파이썬으로 익히는 딥러닝
 
Java Class File Format
Java Class File FormatJava Class File Format
Java Class File Format
 
Swift2
Swift2Swift2
Swift2
 
I phone 2 release
I phone 2 releaseI phone 2 release
I phone 2 release
 
하스켈 프로그래밍 입문
하스켈 프로그래밍 입문하스켈 프로그래밍 입문
하스켈 프로그래밍 입문
 
Python datatype
Python datatypePython datatype
Python datatype
 
파이썬 언어 기초
파이썬 언어 기초파이썬 언어 기초
파이썬 언어 기초
 
eclipse에서 intelliJ IDEA로
eclipse에서 intelliJ IDEA로eclipse에서 intelliJ IDEA로
eclipse에서 intelliJ IDEA로
 
불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14 불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14
 
[A1]루비는 패셔니스타
[A1]루비는 패셔니스타[A1]루비는 패셔니스타
[A1]루비는 패셔니스타
 
Python
PythonPython
Python
 

Python programming for Bioinformatics

  • 1. 앞서가는 생명정보분석을 위한 파이썬 프로그래밍 Hyungyong Kim E-mail_hygkim@insilicogen.com R&D Center, Insilicogen, Inc.
  • 2. 파이썬 설치 • 강의 전 아래 웹사이트에서 파이썬 프로그램을 다운 로드 받아 설치해주세요. • http://www.python.org • Download “Python 2.7.3 Windows Installer” • 설치 후, ;C:Python27 를 PATH 환경변수에 추가
  • 3. 강사소개 • 아주대학교 생물공학과 93 • 생물정보훈련과정 1기 (2000년) • ㈜바이오인포메틱스 • 국립축산과학원 생물정보실 • 숭실대학교 생명정보학과 • ㈜인실리코젠 • LabKM, KinMatch, Ontle • 6.25전사자 유전자정보 검색시스템 • 실종아동등찾기 DNA정보 검색시스템 • 가축유전자원종합관리시스템 http://biohackers.net http://yong27.biohackers.net http://twitter.com/yong27
  • 4. 앞서가는 생물정보 분석 • 머리속의 아이디어를 빠르게 구현 • Battery included. 이미 만들어진 라이브러리 이용 • Prototype  Product
  • 5. 교육 구성 • 기본문법 • 기본 실습문제 – Python introduction – 구구단 함수 – Data type – 이차방정식 근의 공식 – Control flow – 단어빈도수 계산 – Function, Module, Package – String formatting • 객체지향과 고급기능 • 객체지향 문제 – Exception and Test – FASTA 서열 다루기 – Class – Decorator, Iterator, Generator – Standard libraries
  • 7. “미래는 창조적이지 않은 모든 일들을 기술이 대체할 것이다.”
  • 8.
  • 9. Computer language • Information is a sequence (order) • How can we manage it? • Computer language is for it by mimic human’s language • History – Machine language – Assembly – Compiled language (C,…) – Interpreter language (Java, Python,…)
  • 10. Operating System • Unix (linux) • MS-Windows • Mac OS X • Python runs everywhere
  • 11. What is Python? • 1991’s Guido Van Rossum • Free and Open source • For easy language • Object oriented scripting • Dynamic typing • Interpreter • Glue language
  • 12. Why Python? • Easy object oriented • Easy to learn • Prototyping • Battery included • Portable • Extensible • Powerful internal data structure
  • 14. Python applications • 아나콘다 • 구글의 3대 언어가운데 하나 • NASA • Biopython • Django – Pinterest, Instagram
  • 15. Python applications • Web programming – Django, Turbo gears • Network programming – Twisted • GUI – wxPython, PyQt • Game - pygame • Database – Oracle, MySQL, PostgreSQL, sqlite • Scientific and numeric – Numpy, Scipy
  • 16. Python version • 3.2.3 • 2.7.3 • 2.6 • 2.5 • 2.4 … • 1.5
  • 17. Python implementation • Cpython (C) • Pypy (python) • Jython (java) • Parrot (perl) • IronPython (.NET)
  • 19. Variables • 첫문자가 “_” 혹은 영문자, 두번째 문자부터는 숫자도 가능, 대 소문자 구분 • 예약어는 안됨 (import keyword) • 내장함수 이름은 피한다. • “a = 1” – 파이썬에서는 모든 것이 객체 – 객체에 이름부여
  • 20. Python internal data types • Numeric types – Integer, Long, Float, Decimal, Complex • Sequence types – String, Unicode, List, Tuple • Collection types – Dictionary, Set • Etc – Boolean
  • 21. Numeric types • int, long, float, complex • +, -, *, /, //, %, ** • Builtin functions : abs, divmod, pow • For advanced calculation, use import math
  • 22. Integer and Long • Integer and long literal – ~L : Long – 0b~ : 2진수(bin) : 0b101  5 – 0o~ : 8진수(oct) : 011  9 – 0x~ 16진수(hex) : 0xa  10 • Long merged to int in python3
  • 23. Float • 3.14 10. .001 1e100 3.14e-10 0e0 • Builtin functions : round • Float is not precise number • Use Decimal but it is slow
  • 24. Complex • 3.14j 10.j 1e100j 3+4J • Method : conjugate, real, imag
  • 25. Method? • In Python, all is object • Object has attributes. Use “.” for access • Some attribute is method. Use “()” for call • a = 27 • dir(a) • help(a) • a.real • a.imag • a.conjugate()
  • 26. Sequence types • Immutable : String, Unicode, Tuple • Mutable : List
  • 27. Sequencing indexing/slicing -4 -3 -2 -1 MyStr = HEL LO WO R L D ! 0 1 2 3 4 5 6 7 8 9 10 11 12 MyStr[1]  “E” MyStr[3:5]  “LO” MyStr[6]  “W” MyStr[8:-1]  “RLD” MyStr[-1]  “!” MyStr[9:]  “LD!” MyStr[:4]  “HELL” MyStr[:]  “HELLO WORLD!”
  • 28. String • It is a byte stream • Methods : capitalize, center, count, endswith, startswith, find, index, join, strip, split, zfill • Bach slash is special – n : ASCII linefeed – t : ASCII horizontal tab • String literals – r~ : raw string (back slash is not escaping) – u~ : unicode
  • 29. Tuple • Immutable sequence of anything • Use “( )”
  • 30. List • Mutable sequence of anything, Use “[ ]”
  • 31. Set • Unordered collection of distinct hashable objects • Mutability – Mutable : set (add, remove) – Immutable : frozenset • Methods : union(|), intersection(&), difference(-), symmetric_difference(^)
  • 32.
  • 33. Dictionary • Mapping object maps hashable values to arbitrary objects. • Mutable • Usages – d = { key : value } – d[key] = value – key in d – d.keys(), d.values(), d.items() – d.update(annother_d)
  • 34. Bool • Boolean type • True or False • All python objects has boolean value
  • 36. Scope • 괄호 {} 대신 들여쓰기로 현 재 범위 규정 • 들여쓰기가 끝나면 해당 Scope 가 끝남을 의미 • 아무것도 안할 때는 pass
  • 37. if statement • bool() 함수로 평가하여, True, False 에 따라 분기 • elif, else 는 옵션
  • 38. if statement • Operator : >, <, >=, <=, !=, == • When string, alphabet order • When sequence type, from first element • When other types, number < dict < list < string < tuple • hasattr • belong check uses “in” statement : when dict, checks keys default • Same object check uses “is” statement • None, 0, 0.0, “”, [], (), {} is False
  • 39. Logical calculation • not • and, or – True and True  True – True and False  False – False and False  False – False or False  False – True or False  True – It returns that value. So can use one line if statement • if a: return b else: return c  a and b or c • all(), any()
  • 40. for statement • Repeat elements in sequence types data
  • 41. for statement • When dict – keys(), values(), items() – Default is keys() • When list – Use [:] copy when self alteration
  • 42. The range() function • range([start,], stop[, step])  list of integers
  • 43. 구구단 출력 print 2, “*”, 1, “=“, 2 * 1
  • 44. The enumerate() function • enumerate(sequence[, start=0])
  • 45. break and continue statement • break : breaks out the loop • continue : next iteration of the loop • else : end without break or continue
  • 46. while statement • Repeat while an expression is true • Used in break, continue, else
  • 47. Fibonacci series • 어떤 사람이 벽으로 둘러싸인 어떤 곳에다 토끼 암수 한 쌍 을 집어 넣었다. 매달 한 쌍의 토끼가 태어나고 또 그 신생 토끼의 쌍이 두 달째부터 새끼를 낳을 수 있다면, 1년 뒤 원 래의 한 쌍으로부터 얼마나 많은 쌍의 토끼가 태어날까?
  • 48. Sort • L.sort(cmp=None, key=None, reverse=False) • Builtin functions: sorted, reversed • cmp(x, y)  -1, 0, 1 • key  compare function • Dictionary sorting (by key, by value)
  • 49. List comprehension • L = [ k*k for k in range(10) if k > 0] • L=[] • for k in range: • if k > 0: • L.append(k*k)
  • 51. Functions 2,4 def pow(a, b): Function name result = a ** b : pow return result 2 ** 4 16
  • 52. Quadratic equation 23x^2 + 43.2x + 34 = 0 2 b b 4ac x 2a
  • 53. Quadratic equation import cmath def quadratic_equation(a, b, c): in_sqrt = cmath.sqrt(b*b – 4*a*c) x1 = (-b + in_sqrt) / (2.0*a) x2 = (-b – in_sqrt) / (2.0*a) return x1, x2 print quadratic_equation(23, 43.2, 34) ((-0.9391304347+0.7722013312j), (-0.9391304347- 0.7722013312j))
  • 56. Globals and locals h=5 def f(): a = h + 10 # Can refer name but not change print a def f(): global h h = h + 10 print h print h
  • 57. Nested function Search names from inside to outside x=2 def F(): x=1 def G(): print x G() F()
  • 58. Arbitrary argument lists def write_multiple_items(file, separator, *args): file.write(separator.join(args)) >>> # Unpacking argument lists >>> range(3,6) [3, 4, 5] >>> args = [3, 6] >>> range(*args) [3, 4, 5]
  • 60. Arbitrary keyword argument def cheeseshop(kind, *args, **kwargs): assert type(args) == list assert type(kwargs) == dict >>> # Unpacking argument dict >>> mydict = {‘client’:’michael’, ‘sketch’:’cap’} >>> mylist = [‘b’, ‘c’] >>> cheeseshop(‘a’, ‘b’, ‘c’, client=‘michael’, sketch=‘cap’) >>> cheeseshop(‘a’, *mylist, **mydict)
  • 61. Various ways for dict • {‘one’:2, ‘two’:3) • dict(one=2, two=3) • dict({‘one’:2, ‘two’:3}) • dict(zip((‘one’, ‘two’), (2, 3))) • dict([[‘two’, 3], [‘one’, 2]])
  • 62. Python functional programming • LISP, Heskel • Function is an object • Recursion • Expression evaluation instead of statement • It can be used in control flow • In Python: map, reduce, filter, lambda, list comprehension (,iterator, generator)
  • 63. Python functional programming >>> def sqr(x): return x*x … >>> def cube(x): return x*x*x … >>> sqr <function sqr at …> >>> a = [sqr, cube] >>> a[0](2) >>> def compose(f, g): return f(g(x)) >>> compose(sqr, cube, 2) 64
  • 64. lambda, map, reduce, filter >>> f = lambda x: x+4 >>> f(3) 7 >>> a = [‘1’, ‘2’, ‘3’] >>> map(int, a) >>> [1, 2, 3] >>> reduce(lambda x, y: x+y, [1,2,3,4,5]) >>> ((((1+2)+3)+4)+5) >>> filter(lambda x: x%2, range(10)) [1, 3, 5, 7, 9]
  • 65. Module  A file containing Python definitions and statements.  The file name  module name (.py)  In fib.py, fib, fib2 functions existed, ◦ from fib import fib, fib2 ◦ fib(3) or ◦ import fib ◦ fib.fib2(3) or ◦ from fib import * ◦ fib(3)
  • 66. import path • That file is in current directory or PYTHONPATH environmental variable • Or import sys sys.path.append(‘/mydirectory’)
  • 67. Module  Byte compile for Virtual Machine ◦ import statement search .pyc first. ◦ If .py is new, recompile it ◦ If use –O option (optimization), it makes .pyo  For reload, use reload(module)  If module was executed program mode, __name__ is ‘__main__’ but module importing, __name__ is module name  So, for scripting (not for importing), use if __name__ == “__main__”: fib(3)
  • 68. Packages • A way of structuring python module namespace by using “dotted module names”
  • 69. Packages import sound.effects.echo sound.effects.echo()… Or from sound.effects import echo echo()… Or from sound.effects import echo as myecho myecho()…
  • 71. Functions for string • str – 비형식적 문자열로 변환 • repr – 형식적 문자열로 변환 • eval – 문자열을 실행 (expression, 식) • exec – 문자열을 실행 (statement, 문) >>> s = 'Hello, world' >>> s1 = repr([1,2,3]) >>> str(s) >>> s1 'Hello, world' „[1, 2, 3]' >>> repr(s) >>> eval(s1) "'Hello, world'" [1, 2, 3] >>> >>> >>> str(0.1) >>> a = 1 '0.1' >>> a = eval(„a + 4‟) >>> repr(0.1) >>> a '0.10000000000000001' 5 >>> >>> exec „a = a + 4‟ >>> a 9
  • 72. String formatting (old style) >>> template = "My name is %s and I have %i won" >>> template % ("yong", 1000) 'My name is yong and I have 1000 won' >>> >>> template = "My name is %(name)s and I have %(money)i won" >>> template % {'name':'yong', 'money':1000} 'My name is yong and I have 1000 won' >>> >>> name = 'yong' >>> money = 1000 >>> template % locals() 'My name is yong and I have 1000 won' >>> >>> import math >>> print 'The value of PI is approximately %5.3f.' % math.pi The value of PI is approximately 3.142. >>>
  • 73. String formatting operation • Similar with sprintf() in C
  • 74. String formatting (new style) 1 >>> template = "My name is {0} and I have {1} won" >>> template.format("yong", 1000) 'My name is yong and I have 1000 won' >>> >>> template = "My name is {name} and I have {money} won" >>> template.format(name=„yong', money=1000} 'My name is yong and I have 1000 won' >>> >>> print 'The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', ... other='Georg') The story of Bill, Manfred, and Georg. >>> >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} >>> for name, phone in table.items(): ... print '{0:10} ==> {1:10d}'.format(name, phone) ... Jack ==> 4098 Dcab ==> 7678 Sjoerd ==> 4127
  • 75. String formatting (new style) 2 "First, thou shalt count to {0}" # References first positional argument "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'. "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "A man with two {0:{1}}".format("noses", 10)
  • 76. Reading and Writing Files >>> f = open(„/tmp/workfile‟, „w‟) >>> print f <open file „/tmp/workfile‟, mode „w‟ at 80a0960> • mode : ‘r’, ‘w’, ‘a’, ‘r+’, ‘b’, ‘rb’, ‘wb’ • Method : read, readline, readlines, write >>> f.read() >>> f.readlines() 'This is the entire file.n' ['This is the first line of the file.n', 'Second >>> f.read() line of the filen'] '„ >>> >>> f.readline() >>> for line in f: 'This is the first line of the file.n' print line, >>> f.readline() This is the first line of the file. Second line 'Second line of the filen' of the file >>> f.readline() >>> '' >>> f.write(str(43))
  • 77. Position in the file • f.tell() : current position • F.seek(offset, from_what) : go there position – from_what : 0 start, 1 current, 2 end >>> f = open('/tmp/workfile', 'r+') >>> f.write('0123456789abcdef') >>> f.seek(5) # Go to the 6th byte in the file >>> f.read(1) '5' >>> f.seek(-3, 2) # Go to the 3rd byte before the end >>> f.read(1) 'd'
  • 78. File close • f.close() : close it and free up any system resource • “with” keyword when free up >>> f.close() >>> f.read() Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: I/O operation on closed file >>> with open('/tmp/workfile', 'r') as f: ... read_data = f.read() >>> f.closed True
  • 79. Standard IO • stdin, stdout, stderr • Command line pipe “>”, “2>”, “<“, “|” def work(input_file, output_file): output_file.write("<") output_file.write(input_file.read()) output_file.write(">") work(open('a.txt'), open('b.txt', 'w')) import sys work(sys.stdin, sys.stdout) ----- python a.py < a.txt > b.txt • Different with sys.argv
  • 80. StringIO • Virtual file on memory from cStringIO import StringIO handle = StringIO(""" > test fasta AGTCAGTC AGTCCCCC """) for line in handle: print line
  • 81. Character encoding • 문자들의 집합(Character set)을 부호화하는것 – ASCII : 7비트, 인코딩 – ISO-Latin1(ISO-8859-1) : 8비트, 대부분의 서구유럽언어 표시 – 한글조합형 – 한글완성형  EUC-KR  CP949 : 2바이트 • 인코딩간 호환문제 • Unicode
  • 82. Unicode • 전세계의 모든 문자를 표시하기 위한 체계 • 목적 : 모든 인코딩 방법을 유니코드로 교체 • 인코딩 – UTF-7 – UTF-8 : 가변문자열 (2바이트 혹은 4바이트) – UTF-16
  • 83. Unicode in Python • ‘a’  str • u‘a’  unicode • ‘a’ + u‘bc’  u‘abc’ • Unicode  Str • encode/decode • Character set
  • 84. Unicode in Python 2 • Python default encoding : ASCII  UTF-8 – Used in unicode file IO • Source code encoding : ASCII – # -*- coding:utf-8 -*- • 한글이 깨진다면, – 저장된 정보의 인코딩 확인 – 디스플레이 환경 (터미널, 에디터, 웹브라우저 등)
  • 85. Hangul examples hangul.py 필요 >>> import hangul >>> haveJongsung = lambda u: bool(hangul.split(u[-1])[-1]) >>> haveJongsung(u'자음')) True >>> haveJongsung(u„자')) False
  • 86. Excersize 임의의 텍스트파일내 단어의 출현 빈도를 조사하여 가장 많 이 출현한 단어부터 정렬하여 출력하는 프로그램 (특수기호 제외, 소문자로 통일) $ python word_frequency.py < input.txt 32 the 28 of 17 boy …
  • 87. Excersize 임의의 FASTA 형식의 파일에 저장된 DNA 서열을 읽어 GC 함량을 계산하시오 (single FASTA format) $ python gc_content.py < input.fasta 0.55
  • 88. Excersize 임의의 FASTA 형식의 파일에 저장된 DNA 서열을 읽어 Reverse complement 서열을 출력하시오 (Single FASTA) $ python reverse_complement.py < input.fasta > seq1 reverse complement AGTCAAGGCCAAGTCCAA AGCAGCAGGAGCCAAGGT
  • 90. Exception • Errors detected during execution
  • 91. Built-in Exceptions • Used by class inheritance • BaseException – SystemExit – KeyboardInterrupt – GeneratorExit – Exception
  • 92. Handling Exceptions • By default, when exception raised, program stopped and show error message • try/except/else/finally statement try: statements… #1 except (exception types): statements… #2 else: statements… #3 finally: statements… #4
  • 95. Handling Exceptions example def dosomething(): a = 1/0 try: dosomething() except ArithmeticError: print „Exception occurred‟
  • 96. Raising Exceptions • “raise” statement allows the programmer to force a specified exception to occur.
  • 97. User-defined Exceptions • Programs may name their own exceptions by creating a new exception class
  • 98. Assert statement • Usually, used when debugging a = 30 margin = 2 * 0.2 assert margin > 10, „not enough margin %s‟ % margin if not margin > 10: raise AssertionException(„not enough margin %s‟ % margin)
  • 99. Unit test 란? • 프로그램을 작은 단위로 쪼개서 그 단위를 테스트하는 전통적인 프로그래 밍 테스팅 방법중의 하나 • 왜 필요한가? • Regression testing 개념 – 인공적인 상황을 가정하고, 테스트모듈이 그 상황을 이용하여, 결과값을 계산한 다. 이때 기대되는 값과, 계산 값이 같은가를 확인한다. – 프로그램이 퇴행하지 않도록 계속적으로 검사한다. – 프로그램이 수정되는 것 뿐만 아니라, 플랫폼이나 주변 환경 등의 요소의 변화 에 의한 퇴행도 검사한다. bioxp
  • 100. Test Driven Development • 테스트가 주도하는 프로그래밍 • 기본 사이클 – Write a test – Make it compile, run it to see it fails – Make it run – Remove duplication bioxp
  • 101. TDD의 장점 • 테스트에는 실제 코드를 어떻게 사용하는지에 대해 작동하는 설명이 들어있다. (인 터페이스가 정의된다.) • 따로 테스트를 할 필요가 없다. • 코드 수정 시 기존의 테스트 코드를 통과하는지 체크되기 때문에 통합적인 테스트 가 유지된다. • 테스트가 용이한 코드가 유지보수관리가 용이하다. • 프로그램이 잘못되었는지를 "빨리" 알 수 있다(혹은 그럴 확률이 높다). (Fail early, often) • 어떤 기능을 구현할 때, 어떻게 사용할지를 먼저 생각하도록 이끄는 역할을 한다. (Programming by intention) • 오랜 시간이 지난 후에 다시 그 코드를 개선해야 할 일이 생길 때(혹은 어쨌던 봐야 할 일이 있을 때), 빨리 접근할 수 있도록 도와준다. (Documentation) bioxp
  • 102. CLASS
  • 103. Object Oriented • Programming paradigms – Procedural programming – Functional programming – Object oriented programming • It’s origin is the modeling of cell • Modeling of real world  Easy maintain • The keys : remove duplication, easy management
  • 104. Example calculate average Name Korean English Math Science smith 80 69 70 88 neo 92 66 80 72 trinity 82 73 91 90 oracle 80 42 100 92
  • 105. Procedural example smith_korean = 80 smith_english = 69 smith_math = 70 smith_science = 88 neo_korean = 92 neo_english = 66 neo_math = 80 neo_science = 88 smith_average = (smith_korean + smith_english + smith_math + smith_science) / 4.0 neo_average = (neo_korean + neo_english + neo_math + neo_science) / 4.0
  • 106. Functional example def average(alist): return sum(alist) / float(len(alist)) smith = { 'korean': 80, 'english': 69, 'math': 70, 'science': 88, } neo = { 'korean': 92, 'english': 66, 'math': 80, 'science': 88, } smith_average = average(smith.values()) neo_average = average(neo.values())
  • 107. Object oriented example class Score: def __init__(self, korea, english, math, science): self.korea = korea self.english = english self.math = math self.science = science def get_average(self): return (self.korea + self.english + self.math + self.science) / 4.0 smith_score = Score(80, 69, 70, 88) smith_average = smith_score.get_average() neo_score = Score(92, 66, 80, 88) neo_average = neo_score.get_average()
  • 108. Class statement • Collection of variables and functions • It is a kind of name space class Person: name = ‘yong’ gender = ‘male’ def get_age(self): return 27 Person.name, Person.get_age()
  • 109. Instance(object) and Class smith_score = Score(80, 69, 70, 88) object = Class() 붕어빵 붕어빵틀
  • 110. Class Person: 클래스 변수 count = 0 def __init__(self, name, gender): 생성자 self.name = name 인스턴스 변수 self.gender = gender Person.count += 1 메쏘드 (인스턴스 함수) def set_age(self, age): self.age = age yong = Person(‘yong’, ‘male’) yong.set_age(27) 객체 메쏘드 호출
  • 111. Constructor, Destructor • Constructor(생성자) : 객체가 만들어질 때 최초 수행되는 함수 class Person: count = 0 def __init__(self, name, gender): self.name = name self.gender = gender Person.count += 1 def __del__(self): Person.count -= 1
  • 112. Operator overloading • __add__(self, other) : + Class MyString: • __sub__(self, other) : - def __init__(self, str): • __mul__(self, other) : * self.str = str def __div__(self, sep): • __div__(self, other) : / return self.str.split(sep) • __mod__(self, other) : % >>> m = MyString(“abcdef”) • __and__(self, other) : & >>> print m / “b” [“a”, “cdef”] • __or__(self, other) : |
  • 113. Inheritance • Is-a relationship. “Man is a person” class Man(Person): def __init__(self, name): Person.__init__(self, name, „male‟) class Woman(Person): def __init__(self, name): Person.__init__(self, name, „female‟) yong = Man(„yong‟) yong.gender, yong.set_age(27)
  • 114. Multiple Inheritance class Singer: def song(self): print “Oh my love~” class ManSinger(Man, Singer): def __init__(self, name): Man.__init__(self, name) yong = ManSinger(„yong‟) yong.song()
  • 115. Subclassing class MyList(list): def __sub__(self, other): L = self[:] for x in other: if x in L: L.remove(x) return L >>> L = MyList([1,2,3,‟spam‟,4,5]) >>> L = L – [„spam‟] >>> print L [1, 2, 3, 4, 5]
  • 116. Polymorphism class Animal: def cry(self): print „…‟ class Dog(Animal): def cry(self): print „멍멍‟ class Duck(Animal): def cry(self): print “꽥꽥” for each in (Animal(), Dog(), Duck()): each.cry()
  • 117. Composition • has-a relationship. class Set(list): def union(self, A): result = self[:] for x in A: if x not in result: result.append(x) return Set(res) A = MySet([1,2,3]) B = MySet([3,4,5]) print A.union(B)
  • 118. Encapsulation • Python do not support complete private • “from module import *” do not import name “_” starting class Encapsulation: z = 10 __x = 1 >>> Encapsulation.z >>> Encapsulation.__x >>> Encapsulation._Encapsulation__x
  • 120. Decorator • 함수를 장식(decoration)하는 함수 def mydecorator(function): @A @B @C def wrapper(*args, **kwargs): def f(): ## do something for decoration …. result = function(*args, **kwargs) return result def f(): …. return wrapper f = A(B(C(f))) def require_int(function): def wrapper(arg): assert isinstance(arg, int) return function(arg) return wrapper @require_int def p1(arg): print arg
  • 121. Decorator • 인수를 가질 수도 있다. def mydecorator(arg1, arg2): def _mydecorator(function): def __mydecorator(*args, **kwargs): #do somethings for decoration result = function(*args, **kwargs) return result return __mydecorator return _mydecorator @mydecorator(1, 2) def f(arg): ….
  • 122. Static method • 인스턴스를 생성하지 않고 클래스 이름으로 직접 호출할 수 있 는 메쏘드 • Instance method는 이처럼 호출하면 unbounded method 오류 class D: def spam(x, y): # self 가 없다. print „static method‟, x, y spam = staticmethod(spam) D.spam(1, 2) class D: @staticmethod def spam(x, y): print „static method‟, x, y
  • 123. Class method • 일반 메쏘드가 첫 인수(self)로 인스턴스 객체를 받는 것에 비해 서, 클래스 메쏘드는 첫 인수로 클래스 객체를 받는다. class C: def spam(cls, y): # self 가 없다. print „class method‟, cls, y spam = classmethod(spam) >>> C.spam(5) class C: __main__.C 5 @classmethod def spam(cls, y): print „class method‟, cls, y
  • 124. get/set property • 멤버 값을 정의할 때 편하게 사용하기 위함 • <예제> degree에 변수에 값을 저장하는데 360도 미만의 범위 에서 정규화 하기 class D(object): def __init__(self): self.__degree = 0 def get_degree(self): return self.__degree def set_degree(self, d): self.__degree = d % 360 degree = property(get_degree, set_degree) d = D() d.degree = 10 # set_degree call print d.degree # get_degree call
  • 125. Iterator • 순차적으로 참조는 하나, 인덱싱에 의한 순서적인 참조는 의미 가 없는 경우  메모리 효율 • iter() 내장함수로 만들며, next() 메쏘드를 갖는다. • 더 이상 넘겨줄 자료가 없으면 StopIteration 예외 >>> I = iter([1,2,3]) >>> I <iterator object at 0x1234556> >>> I.next() 1 >>> I.next() >>> I.next() # 더이상 자료가 없으면 StopIteration 2 Traceback (most recent call last): >>> I.next() File "<pyshell#71>", line 1, in ? 3 I.next() StopIteration
  • 126. Iterator on class • iter(s) 에 의해 s.__iter__() 가 호출되고 반복자 객체를 리턴한 다. • 반복자 객체는 next() 메쏘드를 갖는다. class Seq: def __init__(self, fname): self.file = open(fname) def __iter__(self): return self >>> s = Seq(„readme.txt‟) def next(self): >>> for line in S: line = self.file.readline() print line, if not line: raise StopIteration return line
  • 127. Generator • icon 이란 언어에서 영향을 받음 • 기존의 함수 호출방식 – 인수들과 내부 변수들이 스택을 이용 생성 소멸 • 발생자란 (중단된 시점부터) 재실행 가능한 함수 • 어떤 함수이든 yield 를 가지면 발생자 함수 • 일종의 내맘대로 만드는 iterator def generate_int(n): while True: def generate_int(n): yield n while True: n += 1 return n n += 1
  • 128. Generator example • 피보나치 수열 def fibonacci(a=1, b=1): while 1: yield a a, b = b, a+b t = fibonacci() # t는 반복자 for i in range(10): print t.next(),
  • 129. Generator example • 홀수 집합 만들기 (iterator 이용) class Odds: def __init__(self, limit=None): self.data = -1 self.limit = limit def __iter__(self): return self def next(self): self.data += 2 if self.limit and self.limit <= self.data: raise StopIteration return self.data >>> for k in Odds(20): print k, 1 3 5 7 9 11 13 15 17 19
  • 130. Generator example • 홀수 집합 만들기 (generator 이용) def odds(limit=None): k=1 while not limit or limit >= k: yield k k += 2 >>> for k in odds(20): print k, 1 3 5 7 9 11 13 15 17 19
  • 131. Generator expression • List comprehension >>> [k for k in range(100) if k % 5 == 0] [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95] • Generator expression >>> (k for k in range(100) if k % 5 == 0) <generator object at 0x40190e4c> • Other example >>> sum(x for x in range(1, 20) if x % 2) >>> “, “.join(x for x in [“abc”, “def”] if x.startswith(“a”))
  • 132. Iterator / generator 가 사용되는 곳 • iter() • xrange() • dict.iteritems(), dict.iterkeys(), dict.itervalues() • file은 라인단위의 반복자를 지원한다. • reversed()는 iterator를 받지 않는다.
  • 133. Itertools module • http://docs.python.org/library/itertools.html • Infinite iterator: count, cycle, repeat • Finite iterator: chain, groupby, ifilter,… • Combinatoric iterator: product, permutations, combinations >>> text = “Hello world my world” >>> wd = dict( (k, len(list(v))) for k, v in groupby( sorted(text.split() ), lambda x: x.upper()) )
  • 134. Excersize 임의의 FASTA 형식의 파일에 저장된 DNA 서열을 읽어 Reverse complement 서열을 출력하시오 (Multiple FASTA) $ python reverse_complement.py < input.fasta > seq1 reverse complement AGTCAAGGCCAAGTCCAA AGCAGCAGGAGCCAAGGT > seq2 reverse complement AGTCAAGGCCAAGTCCAA AGCAGCAGGAGCCAAGGT
  • 136. Library? • 특정 기능을 수행하기 위한 모듈 및 패키지  import 하여 사용 • Python libraries – Built-in library : 파이썬 설치시 같이 설치됨 • math, StringIO, random, unittest, re, itertools, decimal • os, sys, subprocess, glob, pickle, csv, datetime, Tkinter, … – 3rd party library : 따로 설치하여 사용해야함 • wxPython, PythonWin, numpy, scipy, matplotlib, Biopython, PIL, BeautifulSoup…
  • 137. os • Miscellaneous operating system interfaces • 운영체제 의존적인 기능들을 일관적으로 사용 • os.name  ‘posix’, ‘nt’, ‘mac’, ‘os2’, ‘ce’, ‘java’, ‘riscos’ • os.environ  시스템 환경변수 사전 • os.chdir  현재 디렉토리 변경 • os.stat  파일의 속성 • os.walk  특정 디렉토리 하위 모든 파일들에 대한 일괄작업 • os.fork  프로세스 분기
  • 138. sys • System-specific parameters and functions • 시스템운영에 관련된 특정 상수값들과 함수 • sys.argv  명령행 인수 • sys.getdefaultencoding()  기본 인코딩 • sys.stdin, sys.stdout  표준입출력
  • 139. Subprocess • Subprocess management • 다른 프로그램 이용하기 – Shell pipeline – Process spawn • Popen, PIPE
  • 140. glob • Unix style pathname pattern expansion • 와일드카드를 이용한 디렉토리내 파일 탐색 – ? : 아무런 문자 하나 – * : 0개 이상의 아무 문자 – [ ] : 사이에 나열된 문자 중 하나 – - : 일정 범위 a-z
  • 141. pickle • Python object serialization • 파이썬 객체를 (파일에) 저장하기 • dump() and load()
  • 142. csv • CSV File Reading and Writing • 표 데이터를 다루는 일반적인 방법 • CSV format : “,” 로 컬럼 구분. ‘ “” ’로 데이터 구분 • reader() and writer()
  • 143. datetime • Basic date and time types • 날짜와 시각(시간)을 다루기 • date, time, datetime, timedelta, tzinfo
  • 144. Tkinter • Python interface to Tcl/Tk • Built-in GUI library, 운영체제 독립
  • 145. wxPython • Advanced GUI library for python • http://www.wxpython.org • 3rd party GUI library, 운영체제 독립 • PythonWin 과 구분
  • 146. numpy , scipy, matplotlib • numpy : 행렬, 벡터방식의 수치해석 • scipy : 각종 과학연산용 라이브러리 • matplotlib : matLab 프로그램의 영향을 받은 차트 라이브러리
  • 147. PIL • Python Image Library • 그래픽이미지 변환 및 수정
  • 148. BeautifulSoup • HTML, XML 문서 파싱 라이브러리 • Invalide 형식도 적절하게 자동 해석
  • 149. BioPython • 생물정보 관련 라이브러리 • 생물서열 관리, 각종 문서형식 파싱, 주요 분석 알고리즘 탑재