Coding/Python 삽질기2017. 7. 8. 01:18

Sleep



import time


beforeTime = time.time()

time.sleep(3) # Sleep 3 seconds

print time.time()-beforeTime


beforeTime = time.time()

time.sleep(0.05) # Sleep 50 ms

print time.time()-beforeTime


'Coding > Python 삽질기' 카테고리의 다른 글

[Python] 날짜 시간 출력 하기  (0) 2017.07.08
[Python] Thread example  (0) 2017.06.30
Python으로 마우스 제어하기  (0) 2017.06.22
Posted by chobocho
Coding/Python 삽질기2017. 6. 30. 01:51

import threading

import time



def count(s, c):

    for i in range(s, c):

        m = '+' + str(i)

        print m

        time.sleep(0.2)


def count2(s, c):

    for j in range(s, c, -1):

        n = '-' + str(j)

        print n

        time.sleep(0.1)



t1 = threading.Thread(target=count ,args=(10,100))

t2 = threading.Thread(target=count2,args=(200,101))

t1.start()

t2.start()

'Coding > Python 삽질기' 카테고리의 다른 글

[Python] Sleep  (0) 2017.07.08
Python으로 마우스 제어하기  (0) 2017.06.22
Python for Windows Extensions  (0) 2017.06.21
Posted by chobocho
Coding/Python 삽질기2017. 6. 22. 00:49

# pymove.py


import win32api

import win32con

import sys


mVersion = "V0.627_20170622"


def clickMouseLeft(x,y):

    win32api.SetCursorPos((x,y))

    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)

    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)


def clickMouseRight(x,y):

    win32api.SetCursorPos((x,y))

    win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTDOWN,x,y,0,0)

    win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP,x,y,0,0)


def moveMouseXY(x,y):

    win32api.SetCursorPos((x,y))



def readDataFile(filename):

    ''' Example of data file

        L 1 2

        R 2 3

        M 3 4

    '''

    with open(filename, 'r') as fp:

        cmdlines = fp.readlines()

    return cmdlines



def parseCommand(cmdlines):

    cmdlist = []

    for c in cmdlines:

        cmd = c.strip().split(" ")

        cmdlist.append(cmd)

    return cmdlist


cmdTable = { 

   'L':clickMouseLeft,

   'R':clickMouseRight,

   'M':moveMouseXY

}


def process(cmdlist):

    for c in cmdlist:

        cmdTable[c[0]](int(c[1]), int(c[2]))


def main(filename):

    cmdlines = readDataFile(filename)

    cmdlist = parseCommand(cmdlines)

    process(cmdlist)


def printHelp():

    print "\n[Help]"

    print "Usage : pymove filename"


if __name__ == '__main__':

    if (len(sys.argv) < 2) or ('-h' in sys.argv[1:]):

        printHelp()

    else:

        main(sys.argv[1])

    print mVersion



'Coding > Python 삽질기' 카테고리의 다른 글

[Python] Thread example  (0) 2017.06.30
Python for Windows Extensions  (0) 2017.06.21
[Python] 진법 변환  (0) 2016.12.27
Posted by chobocho
Coding/Python 삽질기2017. 6. 21. 23:53

Win32관련 Python 라이브러리


Download : https://sourceforge.net/projects/pywin32/


사용처 : Macro 프로그램 제작

'Coding > Python 삽질기' 카테고리의 다른 글

Python으로 마우스 제어하기  (0) 2017.06.22
[Python] 진법 변환  (0) 2016.12.27
단위분수를 소수로 변환하기  (0) 2016.09.07
Posted by chobocho
Coding/Python 삽질기2016. 12. 27. 01:06

진법 변환 하기



  1. 내장 함수를 이용한 진법 변환


num = 255


print int(num)   # 255

print hex(num)   # 0xff

print oct(num)   # 0377

print bin(num)   # 0b11111111



  1. 재귀를 이용한 진법 변환


def convertBase(n, base):

   N = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

   q, r = divmod(n, base)

   if q == 0:

       return N[r]

   else:

       return convertBase(q, base) + N[r]



  1. 루프를 이용한 진법 변환


def convertBase(n, base):

   N = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

   answer = ""

   q = n


   while q!=0:

       q, r = divmod(q, base)

       answer = N[r] + answer


   return answer





Update : 2017.6.28

'Coding > Python 삽질기' 카테고리의 다른 글

Python for Windows Extensions  (0) 2017.06.21
단위분수를 소수로 변환하기  (0) 2016.09.07
[Notepad++] Python 실행하기  (0) 2016.08.28
Posted by chobocho
Coding/Python 삽질기2016. 9. 7. 02:42
def getDecimal(q, size):
    
    if (q < 2):
        return -1
    
    p = 10
    result = "0."
    
    for i in range(size):
        m = p % q
        
        result += str(int(p / q))
        if (m == 0):
            break;
        else:
            p = m * 10
    
    return result
    

    
for i in range(2, 10):
    print(str(i) + " : " + getDecimal(i, 100) )


2 : 0.5

3 : 0.3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333

4 : 0.25

5 : 0.2

6 : 0.1666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666

7 : 0.1428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428

8 : 0.125

9 : 0.1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111

'Coding > Python 삽질기' 카테고리의 다른 글

[Python] 진법 변환  (0) 2016.12.27
[Notepad++] Python 실행하기  (0) 2016.08.28
Cython 설치  (4) 2013.12.15
Posted by chobocho
Coding/Python 삽질기2016. 8. 28. 18:54
1. 배치파일 작성

[ python.bat ]

C:\Users\sje\AppData\Local\Programs\Python\Python35-32\python.exe "%1" 



2. Notepad++ 실행 -> 실행


C:\Work\python.bat $(FULL_CURRENT_PATH)

 




Posted by chobocho
Coding/Python 삽질기2013. 12. 15. 04:02

Cython 설치 ( Mac )

  1. python download ( http://www.cython.org )
  2. sudo python setup.py install
Cython 실습

factorial_100000.pyx ]

def Factorial(int N):
    cdef int checkSize = 5000
    cdef int fi
    cdef int endN
    endN = N / checkSize
    facResult = 1
    for fi in range(1, endN + 1):
        facResult = facResult * reduce(lambda x, y : x * y, range((fi-1)*checkSize+1,fi * checkSize+1))
   
    if ( (endN * checkSize + 1) != (N+1) ):   
        facResult = facResult * reduce(lambda x, y : x * y, range(endN * checkSize + 1, N+1))  
    return facResult


[ setup.py ]

from distutils.core import setup

from Cython.Build import cythonize

setup(
  name = 'Factorial app',
  ext_modules = cythonize("factorial_100000.pyx"),


[ Build ]
python setup.py build_ext —inplace

# 이러면 SO 파일이 생김

[ Sandbox.py ]

import time

from factorial_100000 import Factorial

startTime = time.time()
factorialN = Factorial(10000)

print "runtime is %s"%(time.time() - startTime) 


[ 실행결과 ]



'Coding > Python 삽질기' 카테고리의 다른 글

[Notepad++] Python 실행하기  (0) 2016.08.28
100000! ( 100000 팩토리얼 ) & 1000000! ( 1000000 팩토리얼 )  (0) 2013.06.22
fibonacci 수열  (0) 2013.06.20
Posted by chobocho
Coding/Python 삽질기2013. 6. 22. 04:48

import sys

import time


def Factorial(N):

    checkSize = 5000

    endN = N / checkSize

    facResult = 1

    for fi in range(1, endN + 1):

        facResult = facResult * reduce(lambda x, y : x * y, range((fi-1)*checkSize+1,fi * checkSize+1))

    

    if ( (endN * checkSize + 1) != (N+1) ):    

        facResult = facResult * reduce(lambda x, y : x * y, range(endN * checkSize + 1, N+1))   

    return facResult



number = 100000

startTime = time.time()

factorialN = Factorial(number)


print "runtime is %s"%(time.time() - startTime) 

#print "Factorial %d is %d"%(number, factorialN)


인터넷을 검색 중 100000! 계산에 관한 글을 보고 실습해 본 코드.

2008년 구매한 노트북에서도 3.2초면 계산이 끝난다. ( * 결과 출력 할 때는 "젠틀맨" 뮤비 한 편 보고 나면 된다. )

math.factorial() 함수를 사용하는 것보다, 분할해서 계산하는게 3배 이상 빠르다.



* 참고 : 100000! 관련 KLDP 링크


http://kldp.org/node/129900

http://kldp.org/node/129379

http://kldp.org/node/129116

http://kldp.org/node/129044

http://kldp.org/node/107470



100000! 결과 : 100000.txt


심심해서 추가로 돌려본 1000000! ( 백만 팩토리얼 )

계산은 5분 만에 끝났으나, 출력이 한 시간도 넘게 걸린 듯...


1000000! 결과 : 1000000!.zip





'Coding > Python 삽질기' 카테고리의 다른 글

Cython 설치  (4) 2013.12.15
fibonacci 수열  (0) 2013.06.20
KMP algorithm  (0) 2013.05.06
Posted by chobocho
Coding/Python 삽질기2013. 6. 20. 01:06

tempResult = [0, 1, 1];


def fibonacci (number):

   if ( number == 1 or number == 2):

      return 1

   if ( tempResult[number] == -1 ): 

      result = fibonacci ( number-1 ) + fibonacci ( number-2 )

      tempResult[number] = result

   

   return tempResult[number]

   

      

for idx in range(3,1001):

    tempResult.insert(idx, -1)   

      

for idx in range(1,1001):

    print idx," : ",fibonacci(idx)


위와 같이 사용하면, 재귀일지라도 매우 빠른 속도로 1부터 1000까지의 피보나치 수열의 값을 구할 수 있다.

더 빠르게 계산하는 방법은 아래와 같다.  


def fibonacci2 (number):

   if ( number == 1 or number == 2):

      return 1

   

   previous =  1

   result   =  1

   sum      =  0

   

   for i in range(3, number+1):

       sum = result + previous

       previous = result

       result = sum

       print i," : ",result

       

   return result

 

fibonacci2(1000)    




1-1000까지 피보나치 수열의 값 : finbonacci_1000.txt


Posted by chobocho