오픈서베이의 새로운 결과 분석 서비스인 오픈애널리틱스를 개발하던 중 발생한 자바 메모리 이슈를 계기로 미시적 관점에서 JVM 메모리 할당을 분석/정리했습니다.
구체적으로, Integer / Long 등의 Object 형 타입과, ArrayList, / LinkedList / Set 등의 자료구조의 메모리 사용을 JDK코드 분석과 각종 도구를 통해 측정하고, 이를 효과적으로 사용하기 위한 방법을 탐구합니다.
파이썬 데이터과학 레벨2 - 데이터 시각화와 실전 데이터분석, 그리고 머신러닝 입문 (2020년 이태영)Tae Young Lee
파이썬 데이터과학 레벨2 - 데이터 시각화와 실전 데이터분석, 그리고 머신러닝 입문 (2020년 이태영)
- 코스피 LG유플러스 주가분석, 대한민국 부동산 분석, 강남 아파트 매매 분석, VISA 보고서 분석, 워드클라우드 등
- 국내 어떤 책에서도 다루지 않는 진짜 데이터분석 강의
- (귀차니즘에..) 소수 금융권/대기업/공기업에게만 강의된 자료
오픈서베이의 새로운 결과 분석 서비스인 오픈애널리틱스를 개발하던 중 발생한 자바 메모리 이슈를 계기로 미시적 관점에서 JVM 메모리 할당을 분석/정리했습니다.
구체적으로, Integer / Long 등의 Object 형 타입과, ArrayList, / LinkedList / Set 등의 자료구조의 메모리 사용을 JDK코드 분석과 각종 도구를 통해 측정하고, 이를 효과적으로 사용하기 위한 방법을 탐구합니다.
파이썬 데이터과학 레벨2 - 데이터 시각화와 실전 데이터분석, 그리고 머신러닝 입문 (2020년 이태영)Tae Young Lee
파이썬 데이터과학 레벨2 - 데이터 시각화와 실전 데이터분석, 그리고 머신러닝 입문 (2020년 이태영)
- 코스피 LG유플러스 주가분석, 대한민국 부동산 분석, 강남 아파트 매매 분석, VISA 보고서 분석, 워드클라우드 등
- 국내 어떤 책에서도 다루지 않는 진짜 데이터분석 강의
- (귀차니즘에..) 소수 금융권/대기업/공기업에게만 강의된 자료
2D 컴퓨터비젼에 대한 설명. 영상으로부터 정보를 추출해내는 공학/과학 분과인 컴퓨터비젼의 기술에 대한 쉬운 설명. 파이썬(Python)의 컴퓨터비젼/영상처리 라이브러리인 scikit-image를 주로 활용하였으며 코드를 함께 담음.
R컨퍼런스 발표본 (2014.5.30) 임.
지난 26일(2014/7/26), 지앤선과 KSUG가 함께 진행했던 세미나에서 발표한 람다 관련 내용입니다.
첫 시간에 정대원님이 발표하신 람다 기본에 다루지 않은 내용만 정리했는데 지난 번에 올렸던 자료(http://www.slideshare.net/gyumee/java-8-lambda-35352385)의 후편으로도 볼 수 있을 것 같습니다.
제 발표는 장표만으로 내용을 가늠하기 어려운데 그래도 이번에는 청각 장애인들도 참여한다고 해서 장표에 글자를 많이 넣으려고 했습니다.
데이터 분석 4 - 나만의 배열 기반 LIST, MyArrayList를 만들어보자Jaewook Byun
본 영상은 2021-2 KMOOC-데이터엔지니어링 강의의 원본이며, 강좌 오픈 이후에는 질의 응답 채널으로 이용 예정입니다. 각 Topic에 질문 해주시면 가능한 답은 달아드리도록 하겠습니다.
강의노트 (SlideShare) - https://www.slideshare.net/ssuser4a9113
코드 (GitHub) - https://github.com/JaewookByun/data_engineering
총 11강
구성
- ArrayList 연산
- MyArrayList - 배열 기반 List interface 구현
- LinkedList 연산
- MyLinkedList - 참조 기반 List & Queue interfaces 구현
- HashSet/HashMap 연산
- Lambda Expression
- Stream - Open JDK 15에서 이용가능한 거의 대부분의 연산을 다루려고 노력함
2D 컴퓨터비젼에 대한 설명. 영상으로부터 정보를 추출해내는 공학/과학 분과인 컴퓨터비젼의 기술에 대한 쉬운 설명. 파이썬(Python)의 컴퓨터비젼/영상처리 라이브러리인 scikit-image를 주로 활용하였으며 코드를 함께 담음.
R컨퍼런스 발표본 (2014.5.30) 임.
지난 26일(2014/7/26), 지앤선과 KSUG가 함께 진행했던 세미나에서 발표한 람다 관련 내용입니다.
첫 시간에 정대원님이 발표하신 람다 기본에 다루지 않은 내용만 정리했는데 지난 번에 올렸던 자료(http://www.slideshare.net/gyumee/java-8-lambda-35352385)의 후편으로도 볼 수 있을 것 같습니다.
제 발표는 장표만으로 내용을 가늠하기 어려운데 그래도 이번에는 청각 장애인들도 참여한다고 해서 장표에 글자를 많이 넣으려고 했습니다.
데이터 분석 4 - 나만의 배열 기반 LIST, MyArrayList를 만들어보자Jaewook Byun
본 영상은 2021-2 KMOOC-데이터엔지니어링 강의의 원본이며, 강좌 오픈 이후에는 질의 응답 채널으로 이용 예정입니다. 각 Topic에 질문 해주시면 가능한 답은 달아드리도록 하겠습니다.
강의노트 (SlideShare) - https://www.slideshare.net/ssuser4a9113
코드 (GitHub) - https://github.com/JaewookByun/data_engineering
총 11강
구성
- ArrayList 연산
- MyArrayList - 배열 기반 List interface 구현
- LinkedList 연산
- MyLinkedList - 참조 기반 List & Queue interfaces 구현
- HashSet/HashMap 연산
- Lambda Expression
- Stream - Open JDK 15에서 이용가능한 거의 대부분의 연산을 다루려고 노력함
"파이썬 성능 잠재력을 끌어내는 실용적인 개발 전략서"
미샤 고렐릭,이안 오스발트 지음 / 김영근,오현석 옮김 | 한빛미디어 | 2016년 8월 | 30,000원
★ 파이썬 3 대응
★ 프로토타이핑에서 실무 운영까지 살아가는 파이썬 코드의 비밀
아이디어 무한경쟁이 펼쳐지는 대(大)스타트업 시대! 높은 생산성으로 유명한 파이썬은 최우선 고려사항이다. 한 가지, 컴파일 언어 대비 느린 성능 때문에 성공한 서비스나 성능이 중요한 기능은 컴파일 언어로 다시 작성하곤 한다. 하지만 실무 운영까지 파이썬 코드를 계속 이어가는 방법이 있다면?
이 책은 파이썬을 둘러싼 설계와 작동 원리를 설명하고 이에 기반한 실용적인 구현 전략을 소개한다. 멀티코어 아키텍처와 클러스터의 이점을 활용하려면 어떻게 해야 하는가? 안정성을 잃지 않고 확장하는 방법은 무엇인가? 여러분은 이에 대한 명확한 해법을 찾고 방대한 소셜 데이터까지도 눈부신 속도로 처리해내는 파이썬 코드를 얻게 될 것이다.
★ 주요 내용
● numpy, Cython, 프로파일러 활용하기
● 파이썬의 시선으로 바라보는 컴퓨터 아키텍처 이해하기
● CPU 시간과 메모리 사용량을 프로파일링하여 병목 지점 찾기
● 상황에 맞는 컬렉션으로 효율적인 프로그램 작성하기
● 행렬과 벡터 연산 가속하기
● 네이티브 코드로 컴파일하기
● 대량의 I/O와 연산 동시 수행하기
● 원격 클러스터로 병렬 처리하기
● 적은 메모리로 대규모 데이터 처리하기
PyCon 2014 발표 http://pycon.kr/2014/program/8 자료 입니다. 파이썬을 기반으로 금융데이터(주식시장 데이터)에 대한 이해와 수집/분석을 위한 구체적인 방법들 소개합니다.
- 마켓 데이터 수집과 저장
- 거래소 상장 종목 분석
- 금융 데이터의 측정과 분포
- 야후 파이낸스 활용
- 이동평균, 기술적 분석, 상관분석
- 데이터 시각화
[C++ Korea 2nd Seminar] C++17 Key Features SummaryChris Ohk
C++은 10년 만에 C++11/14를 발표하면서 '모던 C++'이라는 이름으로 발전했습니다. 그만큼 새로운 기능들이 많이 추가되었습니다. 그리고 2017년, C++은 C++17이라는 이름으로 또 한 번의 발전을 준비하고 있습니다. 3년 주기로 빠르게 변화하는 모던 C++에 대비하기 위해, C++17에 추가될 주요 기능들을 살펴보고자 합니다.
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 환경변수에 추가
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
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
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
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()
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
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년 뒤 원
래의 한 쌍으로부터 얼마나 많은 쌍의 토끼가 태어날까?
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)
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.
>>>
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
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
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
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()
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