블로그 이미지
No pain, no gain!
lepoussin

Tag

Notice

Recent Post

Recent Comment

Recent Trackback

Archive

calendar

1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
  • total
  • today
  • yesterday
04-28 14:05
2007. 2. 21. 02:00 Lecture/열혈강의 Python

1. 시퀀스 자료형 : 문자열, 리스트, 튜플
  1) 인덱싱(indexing) : [k]

>>> s = 'abcdef' # 문자열
>>> l = [100, 200, 300] # 리스트
>>> s[0]  # 참조
'a'
>>> s[1]
'b'
>>> s[-1]
'f'
>>> l[1]
200
>>> l[1] = 900 # 치환

  2) 슬라이싱(Slicing) : [s:t]

>>> s = 'abcdef'
>>> l = [100, 200, 300]
>>> s[1:3] # 1번 위치와 3번 위치 사이를 나타냄
'bc'
>>> s[1:] # 1부터 끝까지
'bcdef'
>>> s[:] # 처음부터 끝까지
'abcdef'
>>> s[-100:100] # 범위를 넘어서면 범위 내의 값으로 자동 처리
'abcdef'
>>> l[:-1] # 맨 오른쪽 값을 제외하고 모두
[100, 200]
>>> s[::2] # 2칸 단위로
'ace'
>>> s[::-1] # 거꾸로
'fedcba'

  3) 연결하기(Concatenation) : +

>>> s = 'abc' + 'def'
>>> s
'abcdef'
>>> L = [1, 2, 3] + [4, 5, 6]
>>> L

[1, 2, 3, 4, 5, 6]

  4) 반복하기(Repetition) : *

>>> s = 'Abc'
>>> s * 4
'AbcAbcAbcAbc'
>>> L = [1, 2, 3]
>>> L * 2
[1, 2, 3, 1, 2, 3]

  5) 멤버십 테스트(Membership Test) : in

>>> t = (1, 2, 3, 4, 5)
>>> 2 in t
True
>>> 10 not in t
True
>>> 'ab' in 'abcd' # 문자열인 경우 부분 문자열 확인 가능
True

  6) 길이 정보 : len

>>> l = [1, 2, 3]
>>> len(l)

3

2. 문자열 정의
  1) 한 줄 문자열 : ' or "
  2) 여러 줄 문자열 : ''' or """
  3) 이스케이프 문자

Escape Sequence Meaning
\newline Ignored
\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\a ASCII Bell (BEL)
\b ASCII Backspace (BS)
\f ASCII Formfeed (FF)
\n ASCII Linefeed (LF)
\N{name} Character named name in the Unicode database (Unicode only)
\r ASCII Carriage Return (CR)
\t ASCII Horizontal Tab (TAB)
\uxxxx Character with 16-bit hex value xxxx (Unicode only)
\Uxxxxxxxx Character with 32-bit hex value xxxxxxxx (Unicode only)
\v ASCII Vertical Tab (VT)
\ooo Character with octal value ooo
\xhh Character with hex value hh

  4) 문자열 연산(시퀀스 자료형의 특징 참조)

>>> str1 = 'Firtst String'
>>> str1[0] = 'f' # 변경 불가능(Immutable) 자료형이므로 에러 발생


Traceback (most recent call last):
  File "<pyshell#54>", line 1, in <module>
    str1[0] = 'f'
TypeError: 'str' object does not support item assignment

3. 문자열 변경

>>> s = 'spam and egg'
>>> s = s[:5] + 'cheese' + s[5:]
>>> s
'spam cheeseand egg'

4. 문자열 포매팅(Formatting) : %s, %r, %c, %d, %i, %u, %o, %x, %X, %e, %E, %f, %g, %G

>>> format = 'name = %s, age = %s'
>>> format % ('gslee', 24)
'name = gslee, age = 24'
>>> "%s -- %s -- %d -- %f -- %e" % ((1, 2), [3, 4, 5], 5, 5.3, 101.3)
'(1, 2) -- [3, 4, 5] -- 5 -- 5.300000 -- 1.013000e+002'
>>> print '%(이름)s -- %(전화번호)s' % {'이름': '이강성', '전화번호': 5284}
이강성 -- 5284

5. 문자열 메쏘드

>>> # 대ㆍ소문자로 변환 관련 메쏘드
>>> s = 'i like programming.'
>>> s.upper()
'I LIKE PROGRAMMING.'
>>> s.upper().lower()
'i like programming.'
>>> 'I Like Programming'.swapcase()
'i lIKE pROGRAMMING'
>>> s.capitalize()
'I like programming.'
>>> s.title()
'I Like Programming.'
>>> # 검색 관련 메쏘드
>>> s = 'i like programming, i like swimming.'
>>> s.count('like') # 문자열 s에서 'like'라는 부분문자열이 발생한 횟수를 리턴
2
>>> s.find('like') # 'like'의 offset를 리턴(검색)
2
>>> s.find('my') # 찾는 문자열이 없을 경우 -1 리턴
-1
>>> s.rfind('like') # find와 같지만 문자열 s의 뒤쪽부터 탐색
22
>>> s.index('like')
2
>>> s.index('my') # find와 같지만 찾는 문자열이 없을 경우 예외 발생

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    s.index('my')
ValueError: substring not found

>>> s.rindex('like') # index와 같지만 문자열 s의 뒤쪽부터 탐색
22
>>> s.startswith('i like') # i like로 시작하는 문자열인가?
True
>>> s.endswith('swimming.') # swimming.으로 끝나는 문자열인가?
True
>>> s.startswith('progr', 7) # 7번째 문자열이 progr로 시작하는가?
True
>>> s.endswith('like', 0, 26) # 0부터 26번째 위치 사이의 문자열이 like로 끝나는가?
True
>>> # 편집 및 치환 관련 메쏘드
>>> u = ' spam and ham '
>>> u.strip() # 좌우 공백 제거
'spam and ham'
>>> u.rstrip() # 오른쪽 공백 제거
' spam and ham'
>>> u.lstrip() # 왼쪽 공백 제거
'spam and ham '
>>> '   abd   '.strip()
'abd'
>>> '><>abc<><><>'.strip('<>')
'abc'
>>> '><><abc<><><>\n'.strip('<>')
'abc<><><>\n'
>>> u'\u4000\u4001abc\u4000'.strip(u'\u4000')
u'\u4001abc'
>>> u.replace('spam', 'spam, egg') # 'spam'을 'spam, egg'로 변경
' spam, egg and ham '
>>> # 문자열 분리와 결합 관련 메쏘드
>>> u = '  spam and ham    '
>>> u.split() # 공백으로 분리
['spam', 'and', 'ham']
>>> u.split('and') # 'and로 분리
['  spam ', ' ham    ']
>>> t = u.split()
>>> ':'.join(t) # ':' 문자로 결합
'spam:and:ham'
>>> print '\n'.join(t) # 줄 바꾸기로 결합
spam
and
ham

>>> lines = '''first line
second line
third line'''
>>> lines.splitlines() # 라인 단위로 분리
['first line', 'second line', 'third line']
>>> s = 'one:two:three:four'
>>> s.split(':', 2) # 두 번만 분리
['one', 'two', 'three:four']
>>> s.rsplit(':', 1) # 오른쪽부터 처리
['one:two:three', 'four']
>>> # 정렬 관련 메쏘드
>>> u = 'spam and egg'
>>> u.center(60) # 전체 60문자의 가운데에 맞춤
'                        spam and egg                        '
>>> u.ljust(60) # 왼쪽에 맞춤
'spam and egg                                                '
>>> u.rjust(60) # 오른쪽에 맞춤
'                                                spam and egg'
>>> u.center(60, '-') # 공백 대신 '-' 문자로 채움
'------------------------spam and egg------------------------'
>>> '1\tand\t2'.expandtabs() # 탭(\t)을 8자 공백으로 사용
'1       and     2'
>>> '1\tand\t2'.expandtabs(4)
'1   and 2'
>>> # 구성된 문자열의 특성 유무 파악 관련 메쏘드
>>> '1234'.isdigit()
True
>>> 'abcd'.isalpha()
True
>>> '1abc234'.isalnum()
True
>>> 'abc'.islower() # 소문자인가?
True
>>> 'ABC'.isupper()
True
>>> ' \t\r\n'.isspace() # 공백문자인가?
True
>>> 'This Is A Title'.istitle() # 제목 문자열인가?
True
>>> # 채우기 및 자리 맞추기 관련 메쏘드
>>> s = '123'
>>> s.zfill(5)
'00123'
>>> 'goofy'.zfill(6) # 빈 자리는 0으로 채워짐
'0goofy'

6.. string 모듈

>>> import string
>>> d = string.letters + string.digits
>>> d
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
>>> userid = raw_input('your id : ')
your id : creaplz510
>>> for ch in userid:
 if ch not in d:
  print 'invalid user id'
  break

7. 유니 코드

>>> unicode('한글', 'cp949') # 인코딩을 명시적으로 알려주어야 함
u'\ud55c\uae00'
>>> unicode('한글', 'cp949').encode('utf-8') # 'utf-8' 코드로 변환
'\xed\x95\x9c\xea\xb8\x80'
>>> len('한글과 세종대왕')
15
>>> len(unicode('한글과 세종대왕', 'mbcs'))
8
>>> u = unicode('한글과 세종대왕', 'mbcs')
>>> print u[0]

>>> print u[1]

>>> ord('A') # 문자 'A'의 ASCII 코드값
65
>>> chr(65) # 코드 65에 해당하는 문자
'A'
>>> ord(unicode('가', 'cp949'))
44032
>>> hex(ord(unicode('가', 'cp949')))
'0xac00'
>>> print unichr(0xac00)

>>> print unichr(0xd7a3)

8. 문서 문자열 : 도움말 사용
# file : docstring.py
'''
Module __doc__ string
line1
line2
'''
class Ham:
    "Ham class __doc__ string"
    def func(self):
        "Ham class func __doc__ string"
        pass

>>> import docstring
>>> print docstring.__doc__
Module __doc__ string
line1
line2
>>> print docstring.Ham.__doc__
Ham class __doc__ string
>>> print docstring.Ham.func.__doc__
Ham class func __doc__ string

posted by lepoussin
2007. 2. 20. 19:20 Lecture/열혈강의 Python

1. 기본 자료형
  1) 정수형 상수

>>> a = 23 # 10진 상수
>>> b = 023 # 8진 상수
>>> c = 0x23 # 16진 상수
>>> print a, b, c
23 19 35

  2) 실수형 상수

>>> a = 1.2 # 소수점 포함
>>> b = 3.5e3 # 지수 포함
>>> c = -0.2e-4
>>> print a, b, c
1.2 3500.0 -2e-005
>>> 0.1 # 진법 변환에 의한 에러(repr : 17자리)
0.10000000000000001
>>> print 0.1 # 유효자리수 제한(str : 12자리)
0.1

  3) 롱형 상수

>>> h = 123456789012345678901234567890L
>>> print h * h

15241578753238836750495351562536198787501905199875019052100
>>> octal = 01234L
>>> octal
668L
>>> hexa = 0x123456789L
>>> hexa
4886718345L
>>> 12345678901234567890
12345678901234567890L
>>> print 12345678901234567890
12345678901234567890

  4) 복소수형 상수

>>> a = 4+5j
>>> d = 7-2j
>>> c = 4+5j
>>> d = 7-2j
>>> print c * d
(38+27j)
>>> c.real # 복소수의 실수 부분
4.0
>>> c.imag # 복소수의 허수 부분
5.0
>>> a = 3
>>> b = 4
>>> complex(a, b) # 복소수 생성
(3+4j)
>>> c.conjugate() # 켤레 복소수
(4-5j)

  5) Decimal 자료형

>>> from decimal import *
>>> Decimal(1234) # 정수로 부터 생성
Decimal("1234")
>>> Decimal(1.1)

Traceback (most recent call last):
  File "<pyshell#181>", line 1, in <module>
    Decimal(1.1)
  File "C:\Python25\lib\decimal.py", line 578, in __new__
    "First convert the float to a string")
TypeError: Cannot convert float to Decimal.  First convert the float to a string

>>> a = Decimal('1.1') # 문자열로 부터 생성(실수는 실수로 부터 생성 안 됨)
>>> print a
1.1

2. 연산자
  1) 산술 연산자 : +, -, *, **, /, //, %

>>> 3 + 5
8
>>> 3 - 5.0 # 정수와 실수의 산술 연산 결과는 실수
-2.0
>>> 2 ** 3 # 2 * 2 * 2
8
>>> 2 ** 3 ** 2 # 2 ** (3 ** 2)
512
>>> divmod(5, 3) # (몫, 나머지)
(1, 2)

>>> 5 % 3 # 나머지는 젯수의 부호와 같음
2
>>> 5 % -3
-1
>>> -5 % 3
1
>>> -5 % -3
-2

>>> 5 / 3
1
>>> 5 / -3
-2
>>> -5 / 3
-2
>>> -5 / -3
1

>>> 3 // 4 # 몫 계산
0
>>> 3.0 // 4.0
0.0
>>> -3 // 4
-1
>>> -3 // 4.0
-1.0

>>> 3 / 4 # 나눗셈(일관성 없음)
0
>>> 3.0 / 4.0
0.75
>>> -3 / 4
-1
>>> -3 / 4.0
-0.75

>>> from __future__ import division
>>> 3 / 4

0.75

  2) 관계 연산자 : <, >, <=, >=, ==, !=, <>

>>> a = 1
>>> b = 2
>>> 0 < a < b
True
>>> 'abcd' > 'abd'
False
>>> x = [1, 2, 3]
>>> y = [1, 2, 3]
>>> x == y
True
>>> x is y # 같은 객체를 가르키고 있는지 확인
False

  3) 논리 연산자 : not, and, or
    - 0, 0.0, 0L, 0.0+0.0j, (), {}, [], None, ""은 모두 거짓으로 간주
    - 나머지는 모두 참
    - 'and'와 'or'이 포함된 논리식은 식의 결과 값을 판정하는데 최종적으로 기여한 객체의 값을 식의 값으로 리턴

>>> 1 and 0
0
>>> 1 or 0
1
>>> [] or () # []와 ()이 거짓
()
>>> [] and 1 # []이 거짓이므로 1은 참조할 필요가 없음
[]

  4) 비트 단위 연산자 : <<, >>, &, |, ^, ~

>>> ~5 # 0000...0101
-6
>>> ~-1
# 1111...1111
0
>>> a = 3 # 0000 0011(편의상 8비트만 표시)
>>> a << 2
# 0000 1100(오른쪽이 0으로 채워짐)
12
>>> a = 4
# 0000 0100
>>> a >> 1 # 0000 0010(왼쪽(MSB)이 0으로 채워짐)
2
>>> a = -4
# 1111 1100
>>> a >> 1
# 1111 1110(왼쪽이 1로 채워짐)
-2

3. 수치 연산 함수
  1) 내장 수치 연산 함수
    - abs(x) : x의 절대값
    - int(x) : x를 int(정수)형으로 변환
    - long(x) :  x를 long형으로 변환
    - float(x) : x를 float형(실수형)으로 변환
    - complex(re, im) : 실수부 re와 허수부 im를 가지는 복소수
    - c.conjugate() : 복소수 c의 켤레 복소수
    - divmod(x, y) : (x//y, x%y) 쌍
    - pow(x, y) : x의 y승
  2) math 모듈 : math(실수 연산), cmath(복소수 연산)

>>> import math
>>> math.pi
3.1415926535897931
>>> math.e
2.7182818284590451
>>> math.sin(1.0) # 1.0 라디안에 대한 사인값
0.8414709848078965
>>> math.sqrt(2) # 제곱근
1.4142135623730951
>>> r = 5.0
>>> a = math.pi * r * r
>>> print a
78.5398163397

posted by lepoussin
2007. 2. 20. 13:35 Lecture/열혈강의 Python
1. 변수명 및 예약어
  1) 변수명 : [a-zA-Z_][a-zA-Z0-9_]*

  2) 예약어
and         del         from       not      while   
as           elif         global     or         with    
assert     else       if             pass    yield   
break      except   import     print             
class       exec       in            raise             
continue  finally     is            return            
def          for          lambda   try


2. 파이썬 기초문
  1) 주석문 : # 다음에 나오는 문자들
import sys # 주석

  2) 연속 라인
>>> if (a == 1) and
SyntaxError: invalid syntax
>>> if (a == 1) and \
    (b == 3):
 print  'connected lines'


  3) 치환문 : 우변의 객체 혹은 을 좌변의 이름에 할당하는 것
>>> c, d = 3, 4 # 여러 개를 한꺼번에 치환
>>> x = y = z = 0 # 여러 개를 같은 값 0으로 치환한다.
>>> e = 3.5; f = 5.6 # ; 로 문들을 구분
>>> e, f = f, e # swap
>>> print e, f
5.6 3.5

  4) 확장 치환문
+=      -=      *=      /=      //=     %=
&=      |=      ^=      >>=     <<=     **=

  5) 이름과 객체

3. 문자열로 된 파이썬 코드 실행하기
  1) eval() : 문자열로된 파이썬 식(expression)을 실행
>>> a = 1
>>> a = eval('a + 4')
>>> a
5
  2) exec() : 문자열로 된 문(statement)을 수행
>>> a = 5
>>> exec 'a = a + 4'
>>> a
9

  3) compile() : 문자열을 컴파일하여 파이썬 코드를 리턴

>>> # 식
>>> code = compile('a + 1', '<string>', 'eval')
>>> a = 1
>>> for k in range(10):
 a = eval(code)
>>> a
11

>>> # 단일문
>>> code = compile('a = a + 1', '<string>', 'single')
>>> a = 1
>>> for k in range(10):
 exec code
>>> a
11

>>> # 복합문
>>> s = '''
a = 1
for k in range(10):
 a = a + 1
print a
'''
>>> code = compile(s, '<string>', 'exec')
>>> exec code
11

4. 콘솔 입ㆍ출력
  1) 콘솔 입력
>>> name = raw_input('name?') # 문자열 입력
name?홍순현
>>> print name
홍순현

>>> # 정수나 실수 등의 값 입력
>>> k = int(raw_input('int : '))
int : 89
>>> k
89
>>> 89
89

>>> i = input('int : ')
int : 45
>>> i
45

  2) 콘솔 출력
>>> print 4+5, 4-2
9 2
>>> print 1; print 2
1
2
>>> print 1,; print 2
1 2

5. 자료형의 종류 : 수치형, 문자열, 리스트, 사전, 튜플

6. 변경 가능성
  1) 변경 가능하다(Mutable) : 리스트, 사전
  2) 변경 가능하지 않다(Immutable) : 숫자, 문자열, 튜플

7. 자료형 확인과 기타 자료형 : type(), types 모듈 이용
>>> from types import *
>>> type(123) == IntType
True
>>> type('abc') == StringType
True


8. 메모리 관리 : 자동적으로 쓰레기 수집(Garbage Collection) - 객체의 Reference Count 값 이용

9. 파이썬 제어문
  1) if문

>>> order = 'spagetti'
if order == 'spam':
 price = 500
elif order == 'ham':
 price = 700
elif order == 'egg':
 price = 300
elif order == 'spagetti':
 price = 900
else:
 price = 100
>>> print price

100
  2) for문

>>> for x in range(2, 4):
 for y in range(2, 10):
  print x, '*', y, '=', x*y
 print

2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18

3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27

3) while
>>> while a < 10:
 a = a + 1
 if a < 3: continue
 if a > 10: break
else:
 print 'else block'
else block


10. 함수

>>> def add(a, b):
 return a+b
>>> print add(3, 4)
7
>>> print add([1, 2, 3], [4, 5, 6])
[1, 2, 3, 4, 5, 6]

posted by lepoussin
2007. 2. 16. 15:51 Lecture/열혈강의 Python
1. 파이썬이란?
  - 대화 기능의 인터프리터 언어
  - 동적인 데이터 타입 결정 지원
  - 플랫폼 독립적 언어
  - 개발 기간 단축에 초점을 둔 언어
  - 간단하고 쉬운 문법
  - 고수준의 내장 객체 자료형 제공
  - 메모리 자동 관리
  - 팀워크에 유용
  - 쉬운 유지 보수
  - 많은 수의 라이브러리 제공
  - 짧아지는 코드
  - 높은 확장성
  - 확장(Extending) 및 내장(Embedding) 기능
  - 무료:)

2. 활용분야
  1) 시스템 유틸리티 : POSIX 시스템 콜, 소켓, Perl식, 정규식 등
  2) GUI : Tcl/tk, wxPython, PyQt, PyGTK, MFC, Anygui 등
  3) 인터넷 프로그래밍 : RPC 프로토콜, 웹 애플리케이션 서버, CGI 래퍼, PSP 등  ※ Zope, Google
  4) DB 프로그래밍 : Oracle, DB Ⅱ, Sybase, MySQL 등
  5) 각종 테스트 프로세싱 : 정규식, 유니코드, XML 지원
  6) 기타 : COM 인터페이스, 수치 연산, AI, 그래픽스, 분산 처리 등

3. 파이썬 설치
posted by lepoussin
2007. 2. 6. 18:49 Language/Python

#   ifdef _DEBUG
#    pragma comment(lib,"python24.lib") <-- 수정
#   else
#    pragma comment(lib,"python24.lib")
#   endif /* _DEBUG */

그리고 다음 부분을 주석으로 처리하면 된다.

//#ifdef _DEBUG
//# define Py_DEBUG
//#endif

posted by lepoussin