http://code.activestate.com/recipes/473810-send-an-html-email-with-embedded-image-and-plain-t/



'python' 카테고리의 다른 글

파이썬 계산 속도 향상 psyco  (0) 2012.07.13
기본 자료형  (0) 2012.05.25
파이썬 개발 환경 구성  (0) 2012.05.23
토큰 분리  (0) 2012.05.21
python ascii character to int, int to ascii character  (0) 2012.05.20
Posted by Нуеоп

psyco


'python' 카테고리의 다른 글

python send email with html, image  (1) 2012.11.29
기본 자료형  (0) 2012.05.25
파이썬 개발 환경 구성  (0) 2012.05.23
토큰 분리  (0) 2012.05.21
python ascii character to int, int to ascii character  (0) 2012.05.20
Posted by Нуеоп
2012. 5. 25. 17:19

파이썬에서 자료형은 크게 4가지로 분류할 수 있다.

동적 타입 언어이기 때문에 변수 사용시 타입 선언이 필요없다.


c언어에서는 변수 선언시 타입을 명시해야 한다.

int a;

double b;


반면 파이썬은 동적 타입 언어이기 때문에 변수 사용시 타입 선언이 필요없다.

그리고 변수의 타입이 바뀔수도 있다.

>>> a = 5

>>> print type(a)

<type 'int'>

>>> a = 4.0

>>> print type(a)

<type 'float'>

>>> a = 'hello'

>>> print type(a)

<type 'str'>

>>> a = [1,2,3]

>>> print type(a)

<type 'list'>



Numeric


기본적으로 정수형, 실수형이 있고, 허수형도 지원한다.

정수형은 이론상 크기 제한이 없다.

2.x에서는 c언어에서의 int형보다 큰 수는 Long로 처리하고, 나머지는 int형으로 처리하지만, 3.x에서는 모두 Long으로 처리한다.

>>> n = 1236784319*78321919693185

>>> print n

96867322110508499166015

이런식으로 42억을 넘는 수도 별도의 처리 과정없이 사용 가능하다.


허수형도 기본 자료형으로 제공하는데, 3+5j 이런식으로 표기한다.

>>> a = 3+5j

>>> b = 4-2j

>>> print a*b

(22+14j)


허수 a의 실수부와 허수부를 알아내기 위해선, 다음과 같이 사용해볼 수 있다.

>>> a.real

3.0

>>> a.imag

5.0


허수 a의 켤레복소수도 conjugate() 메소드를 이용하면 된다.

>>> print a.conjugate()

(3-5j)



List


리스트는 여러 자료를 순서대로 저장하는 자료형이다. 배열이나 링크드리스트쯤으로 생각하면 된다. 이 리스트에 넣을 수 있는 자료는 제한이 없다.


한 리스트 안에 정수, 실수, 문자열, 또 다른 리스트, 클래스 객체 등 여러가지를 넣을 수 있다.



배열처럼 원하는 순서의 값에 접근할 수 있다.


리스트는 기본적으로 [ ] 대괄호를 쓴다.

>>> my_list = [ 10, 3.14, 30, 'hello' ]

>>> print my_list

[10, 3.14, 30, 'hello']


Indexing 인덱싱

원하는 인덱스의 값의 접근은 c언어의 배열처럼 대괄호 [ ] 안에 인덱스 넘버를 이용한다.

>>> print my_list[0]

10

>>> print my_list[1]

3.14


인덱스는 0부터 시작한다. 맨 마지막 인덱서의 접근은 -1로 해도 된다. -2는 맨 마지막에서 2번째 인덱스를 의미한다. 

>>> print my_list[-1]

'hello'

>>> print my_list[-2]

30


기본적으로 리스트끼리 + 연산이 가능하다.

>>> L1 = [1,2,3,4]

>>> L2 = ['a','b','c']

>>> print L1+L2

[1, 2, 3, 4, 'a', 'b', 'c']


리스트에 담겨진 객체의 숫자를 알고 싶으면 len( )를 사용하면 된다.

>>> print my_list

[ 10, 3.14, 30, 'hello' ]

>>> len( my_list )

4


리스트에 객체를 추가하려면 append() 메소드를 사용한다.

>>> my_list.append( 'world' )

>>> print my_list

[10, 3.14, 30, 'hello', 'world']


그밖에 리스트 관련 메소드는 다음과 같다.

 append(x)

 리스트 맨 마지막에 x를 추가한다.

 count(x)

 리스트에 x의 갯수를 리턴한다.

 extend(L)

 리스트에 다른 리스트 L을 합친다.

 index(x)

 x가 있는 위치를 리턴한다. 없을 경우 예외 발생. 여러개 있는 경우 처음에 나온 위치 리턴.

 insert(i, x)  i번째에 x를 추가한다.
 pop(), pop(i)  i번째 혹은 맨 마지막 객체를 리스트에서 제거한다.

 remove(x)

 리스트에 x를 찾아 제거한다. x가 없을 경우 예외 발생

 reverse()

 리스트를 역순으로 정렬한다.

 sort()  리스트를 정렬한다.


리스트의 i번째 값을 수정하는 방법은, i번째에 대입하면 된다.

>>> my_list[1] = 3.14159

>>> print my_list

[10, 3.14159, 30, 'hello', 'world']



Slicing 슬라이싱

다음과 같은 리스트를 만들어보자

L = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

'c', 'd', 'e', 'f', 2번째부터 6번째 전까지 접근하고 싶은경우 [2:6] 처럼 접근하면 된다.

>>> L = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

>>> print L[2:6]

['c', 'd', 'e', 'f']


즉 ':'를 기준으로 시작 인덱스와 끝 인덱스를 지정하면 해당 리스트를 반환한다.

List[start:end]

시작 인덱스나 끝 인덱스를 생략할 경우, 각각 처음과 끝을 의미한다.


 L[2:6]

 2번째부터 6번째 전까지

 L[ :6]

 처음부터 6번째 전까지

 L[2: ]

 2번째부터 마지막까지
 L[ : ]  처음부터 마지막까지


슬라이싱할때 step를 지정할 수도 있다.

List[start:end:step]

start부터 end까지 step만큼 건너뛰며 값을 취한다. 생략할경우 기본 1로 취급하는데, 2로 명시 할 경우 다음이 2칸씩 건너뛰며 출력한다.

>>> print L[0:7:2]

['a', 'c', 'e', 'g']


step 값으로 음수를 넣을 경우 반대 방향으로 값을 취한다.

>>> print L[::-1]

['g', 'f', 'e', 'd', 'c', 'b', 'a']

>>> print L[::-2]

['g', 'e', 'c', 'a']


다음과 같이 응용이 가능하다.

>>> L = L[:3] + L[3::-1]

>>> print L

['a', 'b', 'c', 'd', 'c', 'b', 'a']


String


Tuple


Dictionary




'python' 카테고리의 다른 글

python send email with html, image  (1) 2012.11.29
파이썬 계산 속도 향상 psyco  (0) 2012.07.13
파이썬 개발 환경 구성  (0) 2012.05.23
토큰 분리  (0) 2012.05.21
python ascii character to int, int to ascii character  (0) 2012.05.20
Posted by Нуеоп

1. 파이썬 설치

(1) 버전 선택

2.7 버전과 3.2 버전 큰 차이는 없습니다. 일단 배우는 단계이니 2.7을 선택하시고, 32bit로 진행하시면 되겠습니다.

2.7과 3.2는 크게는 print 의 사용법 변화, 유니코드 처리 방식인데, 2.7에선 print 이후에 출력할 객체를 쓰고 

print 'hello world'

3.2에선 print도 함수로 편입되어 괄호를 꼭 써주어야 합니다. (2.7에서도 괄호를 써도 됩니다.)

print ('hello world')

주로 이 print때문에, 2.7에서 작성된 코드가 3.2에서 작동하지 않게되는 원인이 됩니다.

2to3이라는 2.x 버전 코드를 3.x 버전에서 작동되게 자동으로 변경해주는 라이브러리가 있긴합니다.


그럼 3.2버전으로 하지 왜 2.7버전으로 하느냐 ?

상당수의 파이썬 3rd-party 라이브러리들이 2.7버전으로 만들어져 있습니다.

더 큰 이유로는 파이썬의 가장 큰 영향을 주고고 받는 Google이 2.x 버전을 추천하고고 있는 점입니다. 같은 이유로, 64bit용 파이썬 보단 32bit용 파이썬이 조금더 골치 아픈일이 적습니다.


아직까진 2.x가 주류버전이지만 언젠간 3.x로 넘어갈것입니다. 따라서 당장은 2.x를 하더라도 2.x와 3.x의 차이점을 알고 유의해서 공부하는것이 제일 좋습니다.


(2) 다운로드 및 설치

windows 기준

http://www.python.org/download/ 에서 해당 버전 다운로드 및 설치




(3) 환경설정

제어판 -> 시스템 -> 고급 시스템 설정 -> 환경변수 -> 시스템 변수 

PYTHONPATH=C:\python27;

PATH=C:\python27; ...


PYTHONPATH는 파이썬 프로그래밍시 import할때의 모듈을 탐색하는 경로이고

PATH는 *.py 실행시 실행 프로그램 검색 경로이다. 즉, PATH에 파이썬 설치 경로를 추가하면,  cmd창에서 python이라고 바로 실행시킬 수 있다.


환경설정은 선택사항이므로, 반드시 할 필요는 없다.


2. Hello world

파이썬은 파이썬 전용 쉘에서 간단한 코드를 테스트 해 볼수 있고,

텍스트 파일에 파이썬 코드를 작성한 후 실행시킬 수도 있다.


우선 위에서 설치한 파이썬 폴더에서 IDLE(Python GUI)를 실행시킨다.

간단하게 다음 코드를 타이핑해서 테스트해본다.

>>> print 'hello world'



[File] - [New Window] (Ctrl+N) 를 선택하면 새로운 텍스트 창이 나온다.

이곳에 원하는 코드를 작성한 후 저장(Ctrl+S), Run Module(F5) 하면 작성한 코드를 실행한다. 참고로 작성한 코드를 저장할 때는 *.py 확장자를 붙여줘야 한다.


3. 간단한 구조

파이썬은 java나 c#처럼 운영체제를 가리지 않고 대부분의 플랫폼에서 동일한 코드로 작동한다. (플랫폼 독립적)

C언어는 작성한 코드를 컴파일하여 최종적으로는 기계어(*.exe)파일을 만들어 실행한다.

컴파일시 컴파일러는 source code를 최적화하여 실행만 하면 되는 기계어를 작성하기 때문에, 이후 이 프로그램을 실행할때는 무척 빠르게 작동한다. 단순히 기계어를 실행만 하면 되기 때문이다.


파이썬은 크게 두가지 방식으로 작동하는데,

첫째는 작성한 코드를 컴파일하지 않고 인터프리터에서 해석하여 바로 작동하는 방식이다.

두번째는 컴파일된 중간 코드를 작성해두고(*.pyc), 이 pyc파일을 실행하는 방식이다.


중간 코드를 작성한 pyc방식이 실행 시간은 조금더 빠르다. 

py2exe 라는 파이썬 모듈을 통해 작성한 파이썬 코드를 바로 실행할 수 있는 *.exe로도 만들수 있다.


파이썬은 동적 타입언어로써, 변수에 타입을 미리 명시하지 않는다.


4. 기타 유용한 에디터

eclipse - pydev

eclipse를 설치한 후 [Help] - [Install New Software...]

Location : http://pydev.org/updates


pyScripter

http://code.google.com/p/pyscripter/downloads/list






'python' 카테고리의 다른 글

파이썬 계산 속도 향상 psyco  (0) 2012.07.13
기본 자료형  (0) 2012.05.25
토큰 분리  (0) 2012.05.21
python ascii character to int, int to ascii character  (0) 2012.05.20
python hex string to int  (0) 2012.05.20
Posted by Нуеоп
2012. 5. 21. 11:55

import re


line = raw_input()

token = re.split('\s*', line)



'python' 카테고리의 다른 글

기본 자료형  (0) 2012.05.25
파이썬 개발 환경 구성  (0) 2012.05.23
python ascii character to int, int to ascii character  (0) 2012.05.20
python hex string to int  (0) 2012.05.20
한글 인코딩 문제  (0) 2012.05.19
Posted by Нуеоп

print ord('a')

>>> 97


print chr(97)

>>> 'a'



'python' 카테고리의 다른 글

파이썬 개발 환경 구성  (0) 2012.05.23
토큰 분리  (0) 2012.05.21
python hex string to int  (0) 2012.05.20
한글 인코딩 문제  (0) 2012.05.19
List 사용시 복사 및 [:] 사용팁  (0) 2012.05.14
Posted by Нуеоп
2012. 5. 20. 11:17

h = "A034BFC3"

n = int(h, 16)



'python' 카테고리의 다른 글

토큰 분리  (0) 2012.05.21
python ascii character to int, int to ascii character  (0) 2012.05.20
한글 인코딩 문제  (0) 2012.05.19
List 사용시 복사 및 [:] 사용팁  (0) 2012.05.14
객체 출력, toString()  (0) 2012.05.14
Posted by Нуеоп
2012. 5. 19. 20:40
Posted by Нуеоп

>>> L1 = [ 1, 2, 3, 4 ]

>>> L2 = L1

>>> L2 [0] = 9

>>> print L1

[ 9, 2, 3, 4 ]

>>> print L2

[ 9, 2, 3, 4 ]

둘다 바뀐다.



>>> L1 = [ 1, 2, 3, 4 ]

>>> L2 = L1[:]

>>> L2 [0] = 9

>>> print L1

[ 1, 2, 3, 4 ]

>>> print L2

[ 9, 2, 3, 4 ]

L1와 L2는 서로 다르다.



print L1[:]

이렇게 할 경우 L1의 처음부터 마지막까지 모든 원소를 리스트로 만든다.

이때 만들어진 리스트는 L1과 별도의 메모리를 차지한다.

'python' 카테고리의 다른 글

python hex string to int  (0) 2012.05.20
한글 인코딩 문제  (0) 2012.05.19
객체 출력, toString()  (0) 2012.05.14
빠른 소인수 분해 (Very Large Number Prime Factorization)  (0) 2012.02.19
빠른 소인수 분해  (0) 2012.02.19
Posted by Нуеоп
2012. 5. 14. 00:57

__str__ 를 이용한다.

class Person(object):

        name = ''

        age = 0

        def __init__(self, name='', age=0):

                self.name = name

                self.age = age

        def __str__(self):

                return 'name = %s, age = %d'%(self.name, self.age)



>>> k = Person( 'kim', '22' )

>>> print k

name = kim, age = 22


'python' 카테고리의 다른 글

한글 인코딩 문제  (0) 2012.05.19
List 사용시 복사 및 [:] 사용팁  (0) 2012.05.14
빠른 소인수 분해 (Very Large Number Prime Factorization)  (0) 2012.02.19
빠른 소인수 분해  (0) 2012.02.19
라빈 밀러 소수판별  (0) 2012.02.19
Posted by Нуеоп
'''
    Factor1
'''
def factor1(n):
    if n == 1: return [1]
    i = 2
    limit = n**0.5
    while i <= limit:
        if n % i == 0:
            ret = factor1(n/i)
            ret.append(i)
            return ret
        i += 1

    return [n]

'''
    Factor2 - Improved Factor1
'''
def factor2(n):
##    yield 1
    i = 2
    limit = n**0.5
    while i <= limit:
        if n % i == 0:
            yield i
            n = n / i
            limit = n**0.5
        else:
            i += 1
    if n > 1:
        yield n

'''
    Factor3 - Pollard Rho Prime Factorization
'''
import random
from Queue import Queue
def gcd(a,b):
    while b:
        a,b=b,a%b
    return a

def rabin_miller(p):
if(p<2):
return False
if(p!=2 and p%2==0):
return False
s=p-1
while(s%2==0):
s>>=1
for i in xrange(10):
a=random.randrange(p-1)+1
temp=s
mod=pow(a,temp,p)
while(temp!=p-1 and mod!=1 and mod!=p-1):
mod=(mod*mod)%p
temp=temp*2
if(mod!=p-1 and temp%2==0):
return False
return True
def brent(n):
    if(n%2==0):
        return 2;
    x,c,m=random.randrange(0,n),random.randrange(1,n),random.randrange(1,n)
    y,r,q=x,1,1
    g,ys=0,0
    while(True):
        x=y
        for i in range(r):
            y,k=(y*y+c)%n,0
        while(True):
            ys=y
            for i in range(min(m,r-k)):
                y,q=(y*y+c)%n,q*abs(x-y)%n
            g,k=gcd(q,n),k+m
            if(k>= r or g>1):break
        r=2*r
        if(g>1):break
    if(g==n):
        while(True):
            ys,g=(x*x+c)%n,gcd(abs(x-ys),n)
            if(g>1):break
    return g

def pollard(n):
        if(n%2==0):
            return 2;
        x=random.randrange(2,1000000)
        c=random.randrange(2,1000000)
        y=x
        d=1
        while(d==1):
            x=(x*x+c)%n
            y=(y*y+c)%n
            y=(y*y+c)%n
            d=gcd(x-y,n)
            if(d==n):
                break;
        return d;
def factor3(n):
    if n==1: 
        return [1] 
    Q_1=Queue()
    Q_2=[]
    Q_1.put(n)
    while(not Q_1.empty()):
        l=Q_1.get()
        if(rabin_miller(l)):
            Q_2.append(l)
            continue
        d=pollard(l)
        if(d==l):Q_1.put(l)
        else:
            Q_1.put(d)
            Q_1.put(l/d)
    return Q_2
    

if  __name__ == "__main__":
    import time
    print 'factor1'
    start = time.time()
    print factor1(200000000000000000000000000009)
    print 'time : ', time.time() - start
    print '------------------------'

    print 'factor2'
    start = time.time()
    print [i for i in factor2(200000000000000000000000000009)]
    print 'time : ', time.time() - start
    print '------------------------'

    print 'factor3'
    start = time.time()
    print factor3(200000000000000000000000000009)
    print 'time : ', time.time() - start
    print '------------------------'


설명

Factor2는 Factor1을 개선한 버전
Factor3은 새로운 방식


실행 결과

factor1
[13430577524641L, 2094523, 89, 47, 47, 43, 29, 29]
time :  6.97499990463
------------------------
factor2
[29, 29, 43, 47, 47, 89, 2094523, 13430577524641L]
time :  4.16300010681
------------------------
factor3
[47L, 47L, 29L, 29L, 43L, 89L, 2094523L, 13430577524641L]
time :  0.0350000858307

'python' 카테고리의 다른 글

List 사용시 복사 및 [:] 사용팁  (0) 2012.05.14
객체 출력, toString()  (0) 2012.05.14
빠른 소인수 분해  (0) 2012.02.19
라빈 밀러 소수판별  (0) 2012.02.19
소인수 분해  (0) 2012.02.19
Posted by Нуеоп
2012. 2. 19. 02:51
1.
def highest_prime_factor(n):
   if isprime(n):
      return n
   for x in xrange(2,int(n ** 0.5) + 1):
      if not n % x:
         return highest_prime_factor(n/x)

def isprime(n):
   for x in xrange(2,int(n ** 0.5) + 1):
      if not n % x:
         return False
   return True

if  __name__ == "__main__":
   import time
   start = time.time()
   print highest_prime_factor(1238162376372637826)
   print time.time() - start

2.
def factor(n):
        if n == 1: return [1]
        i = 2
        limit = n**0.5
        while i <= limit:
                if n % i == 0:
                        ret = factor(n/i)
                        ret.append(i)
                        return ret
                i += 1

        return [n]

2-1.
def factor(n):
    yield 1
    i = 2
    limit = n**0.5
    while i <= limit:
        if n % i == 0:
            yield i
            n = n / i
            limit = n**0.5
        else:
            i += 1
    if n > 1:
        yield n

3.
import random
from Queue import Queue
def gcd(a,b):
    while b:
        a,b=b,a%b
    return a

def rabin_miller(p):
if(p<2):
return False
if(p!=2 and p%2==0):
return False
s=p-1
while(s%2==0):
s>>=1
for i in xrange(10):
a=random.randrange(p-1)+1
temp=s
mod=pow(a,temp,p)
while(temp!=p-1 and mod!=1 and mod!=p-1):
mod=(mod*mod)%p
temp=temp*2
if(mod!=p-1 and temp%2==0):
return False
return True
def brent(n):
    if(n%2==0):
        return 2;
    x,c,m=random.randrange(0,n),random.randrange(1,n),random.randrange(1,n)
    y,r,q=x,1,1
    g,ys=0,0
    while(True):
        x=y
        for i in range(r):
            y,k=(y*y+c)%n,0
        while(True):
            ys=y
            for i in range(min(m,r-k)):
                y,q=(y*y+c)%n,q*abs(x-y)%n
            g,k=gcd(q,n),k+m
            if(k>= r or g>1):break
        r=2*r
        if(g>1):break
    if(g==n):
        while(True):
            ys,g=(x*x+c)%n,gcd(abs(x-ys),n)
            if(g>1):break
    return g

def pollard(n):
        if(n%2==0):
            return 2;
        x=random.randrange(2,1000000)
        c=random.randrange(2,1000000)
        y=x
        d=1
        while(d==1):
            x=(x*x+c)%n
            y=(y*y+c)%n
            y=(y*y+c)%n
            d=gcd(x-y,n)
            if(d==n):
                break;
        return d;
def factor(n):
    #if(rabin_miller(n)):
     #   print n
      #  return
    #d=pollard(n)
    #if(d!=n):
     #   factor(d)
      #  factor(n/d)
    #else:
     #   factor(n)

    Q_1=Queue()
    Q_2=[]
    Q_1.put(n)
    while(not Q_1.empty()):
        l=Q_1.get()
        if(rabin_miller(l)):
            Q_2.append(l)
            continue
        d=pollard(l)
        if(d==l):Q_1.put(l)
        else:
            Q_1.put(d)
            Q_1.put(l/d)
    return Q_2
    
    

if __name__ == "__main__":
    while(True):
        n=input();
        L=factor(n)
        L.sort()
        i=0
        while(i<len(L)):
            cnt=L.count(L[i])
            print L[i],'^',cnt
            i+=cnt 





Update : factor2()가 가장 빠르다.

def factor1(n):
    if n == 1: return [1]
    i = 2
    limit = n**0.5
    while i <= limit:
        if n % i == 0:
            ret = factor1(n/i)
            ret.append(i)
            return ret
        i += 1

    return [n]


def factor2(n):
##    yield 1
    i = 2
    limit = n**0.5
    while i <= limit:
        if n % i == 0:
            yield i
            n = n / i
            limit = n**0.5
        else:
            i += 1
    if n > 1:
        yield n


if  __name__ == "__main__":
    import time
    print 'factor1'
    start = time.time()
    print factor1(200000000000000000000000000009)
    print time.time() - start

    print 'factor2'
    start = time.time()
    print [i for i in factor2(200000000000000000000000000009)]
    print time.time() - start



출처 : http://stackoverflow.com/questions/2403578/fastest-calculation-of-largest-prime-factor-of-512-bit-number-in-python 

'python' 카테고리의 다른 글

객체 출력, toString()  (0) 2012.05.14
빠른 소인수 분해 (Very Large Number Prime Factorization)  (0) 2012.02.19
라빈 밀러 소수판별  (0) 2012.02.19
소인수 분해  (0) 2012.02.19
긴 문자열을 숫자로 바꾸는 코드  (0) 2012.02.19
Posted by Нуеоп
2012. 2. 19. 02:21
def primes(n):
    if n < 2:
        return []

    nums = range(2,int(n))
    p = []

    while nums:
        new_prime = nums[0]
        p.append(new_prime)

        for i in nums[1:]:
            if i % new_prime == 0:
                nums.remove(i)
        nums.remove(nums[0])

    return p

def power_mod(a, b, n):
    if b < 0:
        return 0
    elif b == 0:
        return 1
    elif b % 2 == 0:
        return power_mod(a*a, b/2, n) % n
    else:
        return (a * power_mod(a,b-1,n)) % n
    
def rabin_miller(n, tries = 7):
    if n == 2:
        return True
    
    if n % 2 == 0 or n < 2:
        return False
    
    p = primes(tries**2)

    # necessary because of the test below
    if n in p:
        return True
    
    s = n - 1
    r = 0
    while s % 2 == 0:
        r = r+1
        s = s/2
    for i in range(tries):
        a = p[i]
        
        if power_mod(a,s,n) == 1:
            continue
        else:
            for j in range(0,r):
                if power_mod(a,(2**j)*s, n) == n - 1:
                    break
            else:
                return False
            continue
    return True
Posted by Нуеоп
2012. 2. 19. 02:21
def factorize(n):
    def isPrime(n):
        return not [x for x in xrange(2,int(math.sqrt(n)))
                    if n%x == 0]
    primes = []
    candidates = xrange(2,n+1)
    candidate = 2
    while not primes and candidate in candidates:
        if n%candidate == 0 and isPrime(candidate):
            primes = primes + [candidate] + factorize(n/candidate)
        candidate += 1            
    return primes

'python' 카테고리의 다른 글

빠른 소인수 분해  (0) 2012.02.19
라빈 밀러 소수판별  (0) 2012.02.19
긴 문자열을 숫자로 바꾸는 코드  (0) 2012.02.19
[python] (가명) 속성 및 연산자 메쏘드  (0) 2011.11.12
[python] 비트맵 bitmap 쓰기  (0) 2011.11.04
Posted by Нуеоп
s = raw_input()
x = 0
digit = 1

if len(s) > 10:
    while len(s) >  10 :
        x = x+ long(s[len(s)- 10 :len(s)])*digit
        s = s[0:- 10 ]
        digit = digit*(10** 10 )
    x = x + long(s)*digit
else:
    x = long(s)
print x

'python' 카테고리의 다른 글

라빈 밀러 소수판별  (0) 2012.02.19
소인수 분해  (0) 2012.02.19
[python] (가명) 속성 및 연산자 메쏘드  (0) 2011.11.12
[python] 비트맵 bitmap 쓰기  (0) 2011.11.04
[python] 복소수 complex 사용법  (0) 2011.11.04
Posted by Нуеоп
Class SampleC():
    def __init__(self):
        pass

sample = SampleC()

>>> dir(sample)  # 인스턴스 객체의 속성 + 클래스 객체의 속성
>>> dir(SampleC) # 인스턴스 객체의 속성 + 클래스 객체의 속성 + 슈퍼클래스의 속성

>>> dir([])
>>> dir({})
>>> dir((,))

__repr__
__str__
__add__
__getitem__
__getattr__
__len__
__doc__
__name__
__dict__
__new__
__hash__
__delattr__
__setattr__
__class__
__name__
__call__
__nonzero__
__cmp__
__lt__
__le__
__gt__
__ge__
__eq__
__ne__
__delitem__
__contains__
__iter__
__add__
__sub__
__mul__
__div__
__truediv__
__floordiv__
__mod__
__divmod__
__pow__
__lshift__
__rshift__
__and__
__xor__
__or__
__radd__
__rsub__
__rdiv__
__rmul__
...
__iadd__
__isub__
__imul__
__idiv__
__itruediv__
__ifloordiv__
__imod__
__ipow__
__ilshift__
__irshift__
__iand__
__ixor__
__ior__
__neg__
__pos__
__abs__
__invert__
__complex__
__int__
__long__
__float__
__oct__
__hex__

Data model (Attribute)
http://docs.python.org/reference/datamodel.html
Built-in Functions
http://docs.python.org/library/functions.html
Built-in Types
http://docs.python.org/library/stdtypes.html  
 


'python' 카테고리의 다른 글

소인수 분해  (0) 2012.02.19
긴 문자열을 숫자로 바꾸는 코드  (0) 2012.02.19
[python] 비트맵 bitmap 쓰기  (0) 2011.11.04
[python] 복소수 complex 사용법  (0) 2011.11.04
[python] 삼항연산자 만들기  (1) 2011.11.02
Posted by Нуеоп


import struct, random

#Function to write a bmp file.  It takes a dictionary (d) of
#header values and the pixel data (bytes) and writes them
#to a file.  This function is called at the bottom of the code.
def bmp_write(d,byte):
    mn1 = struct.pack('<B',d['mn1'])
    mn2 = struct.pack('<B',d['mn2'])
    filesize = struct.pack('<L',d['filesize'])
    undef1 = struct.pack('<H',d['undef1'])
    undef2 = struct.pack('<H',d['undef2'])
    offset = struct.pack('<L',d['offset'])
    headerlength = struct.pack('<L',d['headerlength'])
    width = struct.pack('<L',d['width'])
    height = struct.pack('<L',d['height'])
    colorplanes = struct.pack('<H',d['colorplanes'])
    colordepth = struct.pack('<H',d['colordepth'])
    compression = struct.pack('<L',d['compression'])
    imagesize = struct.pack('<L',d['imagesize'])
    res_hor = struct.pack('<L',d['res_hor'])
    res_vert = struct.pack('<L',d['res_vert'])
    palette = struct.pack('<L',d['palette'])
    importantcolors = struct.pack('<L',d['importantcolors'])
    #create the outfile
    outfile = open('bitmap_image.bmp','wb')
    #write the header + the bytes
    outfile.write(mn1+mn2+filesize+undef1+undef2+offset+headerlength+width+height+\
                  colorplanes+colordepth+compression+imagesize+res_hor+res_vert+\
                  palette+importantcolors+byte)
    outfile.close()

###################################    
def main():
    #Here is a minimal dictionary with header values.
    #Of importance is the offset, headerlength, width,
    #height and colordepth.
    #Edit the width and height to your liking.
    #These header values are described in the bmp format spec.
    #You can find it on the internet. This is for a Windows
    #Version 3 DIB header.
    width = 2048
    height = 2048
    d = {
        'mn1':66,
        'mn2':77,
        'filesize':width*height+54,
        'undef1':0,
        'undef2':0,
        'offset':54,
        'headerlength':40,
        'width':width,
        'height':height,
        'colorplanes':0,
        'colordepth':24,
        'compression':0,
        'imagesize':width*height,
        'res_hor':0,
        'res_vert':0,
        'palette':0,
        'importantcolors':0
        }
   
    #Function to generate a random number between 0 and 255
    def rand_color():
        x = random.randint(0,255)
        return x

    #Build the byte array.  This code takes the height
    #and width values from the dictionary above and
    #generates the pixels row by row.  The row_mod and padding
    #stuff is necessary to ensure that the byte count for each
    #row is divisible by 4.  This is part of the specification.
    byte = bytes()
    for row in range(d['height']-1,-1,-1):# (BMPs are L to R from the bottom L row)
        for column in range(d['width']):
            b = rand_color()
            g = rand_color()
            r = rand_color()
            pixel = struct.pack('<BBB',b,g,r)
            byte = byte + pixel
        row_mod = (d['width']*d['colordepth']/8) % 4
        if row_mod == 0:
            padding = 0
        else:
            padding = (4 - row_mod)
        padbytes = bytes()
        for i in range(padding):
            x = struct.pack('<B',0)
            padbytes = padbytes + x
        byte = byte + padbytes
      
    #call the bmp_write function with the
    #dictionary of header values and the
    #bytes created above.
    bmp_write(d,byte)

if __name__ == '__main__':
    main()



참고자료
http://docs.python.org/library/struct.html
http://pseentertainmentcorp.com/smf/index.php?topic=2034.0
http://en.wikipedia.org/wiki/BMP_file_format


'python' 카테고리의 다른 글

긴 문자열을 숫자로 바꾸는 코드  (0) 2012.02.19
[python] (가명) 속성 및 연산자 메쏘드  (0) 2011.11.12
[python] 복소수 complex 사용법  (0) 2011.11.04
[python] 삼항연산자 만들기  (1) 2011.11.02
[python] 집합 Sets  (0) 2011.11.02
Posted by Нуеоп

x1 = 3 + 4j
x2 = 2 - 5j

print x1*x2, x1+x2
(26-7j) (5-1j)

x = 4
y = 6
z = complex(4, 6)
print z
(4+6j)

w = z.conjugate()    # z의 켤레 복소수
print w
(4-6j) 

print (z.real , z.imag)
(4.0, 6.0) 

'python' 카테고리의 다른 글

[python] (가명) 속성 및 연산자 메쏘드  (0) 2011.11.12
[python] 비트맵 bitmap 쓰기  (0) 2011.11.04
[python] 삼항연산자 만들기  (1) 2011.11.02
[python] 집합 Sets  (0) 2011.11.02
[python] 리스트 List  (0) 2011.11.02
Posted by Нуеоп

c 언어에서
a>b ? x : y
의 경우를 python에서 여러가지 방법으로 표현할 수 있다.

방법1.
x if a>b else y

방법2.
(lambda:y, lambda:x)[a>b]()

방법3.
{True:x, False:y}[a>b]

방법4.
(a>b) and x or y

방법5.
((a>b) and [x] or [y])[0]


참고 자료
http://en.wikipedia.org/wiki/Ternary_operation
http://www.python.org/dev/peps/pep-0308/
http://docs.python.org/reference/expressions.html#conditional-expressions

'python' 카테고리의 다른 글

[python] (가명) 속성 및 연산자 메쏘드  (0) 2011.11.12
[python] 비트맵 bitmap 쓰기  (0) 2011.11.04
[python] 복소수 complex 사용법  (0) 2011.11.04
[python] 집합 Sets  (0) 2011.11.02
[python] 리스트 List  (0) 2011.11.02
Posted by Нуеоп
2011. 11. 2. 19:00
S1 = set( L1 )
S2 = set( L2 )

맴버쉽 테스트
item in S1

차집합
S1 - S2

합집합
S1 | S2

교집합
S1 & S2

elements in S1 or S2 but not both
S1 ^ S2
 

'python' 카테고리의 다른 글

[python] (가명) 속성 및 연산자 메쏘드  (0) 2011.11.12
[python] 비트맵 bitmap 쓰기  (0) 2011.11.04
[python] 복소수 complex 사용법  (0) 2011.11.04
[python] 삼항연산자 만들기  (1) 2011.11.02
[python] 리스트 List  (0) 2011.11.02
Posted by Нуеоп
2011. 11. 2. 18:50

L = []

리스트 원소 개수
len( L )

리스트 원소 추가, 삭제
L.append( item )    # L[ len(L) : ] = item 과 같다. 리스트 맨 끝에 item을 추가
L.pop()             # 리스트의 마지막 원소가 리턴되고, 해당 원소는 리스트에서 제거됨
L.pop(i)            # 리스트의 i번째 원소가 리턴되고, 해당 원소는 리스트에서 제거됨
                    # 만약 i가 리스트의 원소의 개수보다 큰 값인 경우 IndexError 예외 발생


L.remove( item )   # 리스트에서 item을 제거, 여러개면, 젤 먼저 나오는 item만 제거, 없는 경우 ValueError 예외 발생
L.insert( i, item )# 리스트의 i번째에 item을 추가, L.insert(len(L),item)은 L.append(item)과 같다
                   # 만약 i가 리스트의 원소의 갯수보다 큰 경우, 가장 마지막에 추가한다.

del L[st:ed]       # 리스트의 st~ed원소를 제거

L.extend( L2 )

리스트 정보
L.index( item )      # 리스트에서 item이 있는 위치를 리턴, 없으면 ValueError 예외 발생
L.count( item )      # 리스트에서 item의 개수를 리턴

리스트 순서 변경
L.sort()
L.reverse()

리스트를 이용한 자료구조
L.append( item )과 L.pop() 을 사용하면 Stack
L.append( item )과 L.pop(0) 을 사용하면 Queue

리스트 내장 List Comprehensions

vec = [2, 4, 6]
[3*x for x in vec]
[3*x for x in vec if x > 3]
[3*x for x in vec if x < 2]
[[x,x**2] for x in vec]
[x, x**2 for x in vec]  # error - parens required for tuples
[(x, x**2) for x in vec]
 
vec1 = [2, 4, 6]
vec2 = [4, 3, -9]
[x*y for x in vec1 for y in vec2]
[x+y for x in vec1 for y in vec2]
[vec1[i]*vec2[i] for i in range(len(vec1))]


참고자료
http://docs.python.org/tutorial/datastructures.html

 


'python' 카테고리의 다른 글

[python] (가명) 속성 및 연산자 메쏘드  (0) 2011.11.12
[python] 비트맵 bitmap 쓰기  (0) 2011.11.04
[python] 복소수 complex 사용법  (0) 2011.11.04
[python] 삼항연산자 만들기  (1) 2011.11.02
[python] 집합 Sets  (0) 2011.11.02
Posted by Нуеоп
이전버튼 1 이전버튼