Lanczos 알고리즘은 Stirlng 공식에 의한 알고리즘 보다 정밀하며, 십진수로 유효숫자 약 15자리 까지는 정확하게 계산해 준다.  단지 exp 함수를 이용하는 부분에서는 exp 함수의 구현에 따라 오차가 더 있을 수 있다.


#!/usr/bin/env python
# -*- encoding:utf-8 -*-

# Filename: testLanczos-01.py
#
#           An approximation for the gamma function by using the Lanczos algorithm
#
# Execute: python testLanczos-01.py
#         or
# Execute: ./testLanczos-01.py
#
# See: http://en.wikipedia.org/wiki/Lanczos_approximation
# See:http://www-history.mcs.st-and.ac.uk/Biographies/Lanczos.html
# See: http://www.thinbasic.com/community/showthread.php?11279-Gamma-function

from cmath import *
 
# Coefficients used by the GNU Scientific Library
g = 7
p = [0.99999999999980993, 676.5203681218851, -1259.1392167224028,
     771.32342877765313, -176.61502916214059, 12.507343278686905,
     -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7]
 
def gamma(z):
    z = complex(z)
    # Reflection formula
    if z.real < 0.5:
        return pi / (sin(pi*z)*gamma(1-z))
    else:
        z -= 1
        x = p[0]
        for i in range(1, g+2):
            x += p[i]/(z+i)
        t = z + g + 0.5
        return sqrt(2*pi) * t**(z+0.5) * exp(-t) * x

def factorial(n):
    if n < 2:
        return 1
    else:
        k = 1
        if n % 2 == 0:
            for i in xrange(n/2):
                k *= (i + 1) * (n - i)
        else:
            for i in xrange(n/2):
                k *= (i + 1) * (n - 1 - i)
            k *= n
        return k

def facto(n):
    if n < 2:
        return 1
    else:
        k = 1
        for i in xrange(2, n + 1):
                k *= i
        return k

if __name__ == "__main__":
    print "gamma(10) = 9! = %s asymptotically" % gamma(10)
    # print "gamma(101) = 100! = %16s asymptotically" % gamma(101)
    print "gamma(101) = 100! = %16s asymptotically" % "{0.real:.15f}{0.imag:+.5f}j".format(gamma(101))

    for i in range(11):
        print "%d! = %d" % (i, factorial(i))

    i = 100
    print "factorial(%d) = %d! = %d" % (i, i, factorial(i))
    print "facto(%d) = %d! = %d" % (i, i, facto(i))

"""
Output:
gamma(10) = 9! = (362880+0j) asymptotically
gamma(101) = 100! = 9.33262154439379e+157+0.00000j asymptotically
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
factorial(100) = 100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
facto(100) = 100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
"""



Posted by Scripter
,

 

* 리눅스의 Python 2.6 으로 실행한 결과

Python 2.6.5 (r265:79063, Oct  1 2012, 22:04:36)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = complex(1, 2./3)
>>> x
(1+0.66666666666666663j)
>>> "{0.real:.5}+{0.imag:.5}j".format(x)
'1.0+0.66667j'
>>> "{0.real:.5f}{0.imag:+.5f}j".format(x)
'1.00000+0.66667j'
>>> print "{0.real:.5f}{0.imag:+.5f}j".format(x)
1.00000+0.66667j
>>> "{0.real:.5f}{0.imag:+.5f}j".format(complex(1, -2./3))
'1.00000-0.66667j'
>>> print "{0.real:.5f}{0.imag:+.5f}j".format(complex(1, -2./3))
1.00000-0.66667j
>>> format(1+1j, '')
'(1+1j)'
>>> print format(1+1j, '')
(1+1j)

 

 

* 윈도우의 Python 2.7 로 실행한 결과   (Python 2.6의 경우와 동일함)

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> x = complex(1, 2./3)
>>> x
(1+0.6666666666666666j)
>>> "{0.real:.5}+{0.imag:.5}j".format(x)
'1.0+0.66667j'
>>> "{0.real:.5f}{0.imag:+.5f}j".format(x)
'1.00000+0.66667j'
>>> print "{0.real:.5f}{0.imag:+.5f}j".format(x)
1.00000+0.66667j
>>> "{0.real:.5f}{0.imag:+.5f}j".format(complex(1, -2./3))
'1.00000-0.66667j'
>>> print "{0.real:.5f}{0.imag:+.5f}j".format(complex(1, -2./3))
1.00000-0.66667j
>>> format(1+1j, '')
'(1+1j)'
>>> print format(1+1j, '')
(1+1j)

 

 

* 윈도우의 Python 3.2 로 실행한 결과   (결과는 print() 함수의 사용법 차이 외에는 Python 2.7의 경우와 동일함)

Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> x = complex(1, 2./3)
>>> x
(1+0.6666666666666666j)
>>> "{0.real:.5}+{0.imag:.5}j".format(x)
'1.0+0.66667j'
>>> "{0.real:.5f}{0.imag:+.5f}j".format(x)
'1.00000+0.66667j'
>>> print( "{0.real:.5f}{0.imag:+.5f}j".format(x) )
1.00000+0.66667j
>>> print( "{0.real:.5f}{0.imag:+.5f}j".format(complex(1, -2./3)) )
1.00000-0.66667j
>>> format(1+1j, '')
'(1+1j)'
>>> print( format(1+1j, '') )
(1+1j)

 

 

Posted by Scripter
,


* pyglet 을 이용하는 간단한 Python 소스 (소스파일명: testpyglet.py)

import pyglet

window = pyglet.window.Window()

label = pyglet.text.Label('Hello, world',
                          font_name='Times New Roman',
                          font_size=36,
                          x=window.width//2, y=window.height//2,
                          anchor_x='center', anchor_y='center')
@window.event
def on_draw():
    window.clear()
    label.draw()

pyglet.app.run()

실행 결과:




* pyglet 을 이용하여 한글을 출력하는 Python 소스 (소스파일명: testpyglet2.py)
(소스파일을 저장시 반드시 UTF-8 인코딩으로 저장해야 한다)

# coding: utf-8

import pyglet

window = pyglet.window.Window()

label = pyglet.text.Label(u'Hello, world! 안녕하세요?',
                          font_name='맑은 명조',
                          font_size=24,
                          x=window.width//2, y=window.height//2,
                          anchor_x='center', anchor_y='center')

@window.event
def on_draw():
    window.clear()
    label.draw()

pyglet.app.run()


실행 결과:


Posted by Scripter
,
Python 2.x  에서는 print 가 def, for, return 들 처럼 하나의 키워드(예약어)이지만,
Python 3.x 에서는 print 가 하나의 함수이므로 반드시 소괄호를 붙여서 print( ..... )  처럼 써야 한다.


* 파이썬 버전 확인:
--------------------------
python3.2
Python 3.2.1 (v3.2.1:ac1f7e5c0510, Jul  9 2011, 01:03:53) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Cannot read termcap database;
using dumb terminal settings.
>>>


* Python 3.2 용 소스 파일: first-sample-2.py
#!/usr/local/bin/python3.2
# coding: utf8

from math import *

def lg(x):
    return log(x)/log(2)
    
def log10(x):
    return log(x)/log(10)
    
print("이 파이썬 소스는 Mac Lion 에서 TextWrangler 편집기를 사용하여 작성되었음!")
print("----------------")
print("수학식 계산하기:")
print("----------------")
print("pi + e =", pi + e)
print("pi * e =", pi * e)
print("sqrt(pi) + sqrt(e) =", sqrt(pi) + sqrt(e))
print("sqrt(pi + e) =", sqrt(pi + e))
print("sqrt(pi) - sqrt(e) =", sqrt(pi) - sqrt(e))
print("sqrt(pi - e) =", sqrt(pi - e))
print("sin(pi) =", sin(pi))
print("cos(pi) =", cos(pi))
print("tan(pi) =", tan(pi))
print("log(e) = ln(e) =", log(e))
print("lg(2) = log2(2) =", lg(2))
print("log10(1.0/10) =", log10(1.0/10))
print("pow(2, 10) =", pow(2, 10))
print("2**10 =", 2**10)
print("2**100 =", 2**100)
print("2**1000 =", 2**1000)
# print("2**10000 =", 2**10000)
# print("2**100000 =", 2**100000)
print("len(str(2**100000)) =", len(str(2**100000)))



* Max 에서 TextWrangler 를 써서 편집한 화면:




* 소스 파일에 실행 모드 설정하기:
 chmod +x firtst-sample-2.py

* 실행 및 실행 결과:
./first-sample-2.py
이 파이썬 소스는 Mac Lion 에서 TextWrangler 편집기를 사용하여 작성되었음!
----------------
수학식 계산하기:
----------------
pi + e = 5.859874482048838
pi * e = 8.539734222673566
sqrt(pi) + sqrt(e) = 3.421175121605644
sqrt(pi + e) = 2.420717761749361
sqrt(pi) - sqrt(e) = 0.12373258020538769
sqrt(pi - e) = 0.6506234126825963
sin(pi) = 1.2246467991473532e-16
cos(pi) = -1.0
tan(pi) = -1.2246467991473532e-16
log(e) = ln(e) = 1.0
lg(2) = log2(2) = 1.0
log10(1.0/10) = -0.9999999999999998
pow(2, 10) = 1024.0
2**10 = 1024
2**100 = 1267650600228229401496703205376
2**1000 = 1071508607186267320948425049060001810561404811705533607443750388370351051
12493612249319837881569585812759467291755314682518714528569231404359845775746985748
03934567774824230985421074605062371141877954182153046474983581941267398767559165543
946077062914571196477686542167660429831652624386837205668069376
len(str(2**100000)) = 30103


 
Posted by Scripter
,

* 파이썬 버전 확인:
--------------------------
python
Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Cannot read termcap database;
using dumb terminal settings.
>>>


* Python 2.7 용 소스 파일: first-sample.py
#!/usr/local/bin/python
# coding: utf8

from math import *

def lg(x):
    return log(x)/log(2)
    
def log10(x):
    return log(x)/log(10)
    
print "이 파이썬 소스는 Mac Lion 에서 TextWrangler 편집기를 사용하여 작성되었음!"
print "----------------"
print "수학식 계산하기:"
print "----------------"
print "pi + e =", pi + e
print "pi * e =", pi * e
print "sqrt(pi) + sqrt(e) =", sqrt(pi) + sqrt(e)
print "sqrt(pi + e) =", sqrt(pi + e)
print "sqrt(pi) - sqrt(e) =", sqrt(pi) - sqrt(e)
print "sqrt(pi - e) =", sqrt(pi - e)
print "sin(pi) =", sin(pi)
print "cos(pi) =", cos(pi)
print "tan(pi) =", tan(pi)
print "log(e) = ln(e) =", log(e)
print "lg(2) = log2(2) =", lg(2)
print "log10(1.0/10) =", log10(1.0/10)
print "pow(2, 10) =", pow(2, 10)
print "2**10 =", 2**10
print "2**100 =", 2**100
print "2**1000 =", 2**1000
# print "2**10000 =", 2**10000
# print "2**100000 =", 2**100000
print "len(str(2**100000)) =", len(str(2**100000))


* Max 에서 TextWrangler 를 써서 편집한 화면:




* 소스 파일에 실행 모드 설정하기:
 chmod +x firtst-sample.py

* 실행 및 실행 결과:
./first-sample.py
이 파이썬 소스는 Mac Lion 에서 TextWrangler 편집기를 사용하여 작성되었음!
----------------
수학식 계산하기:
----------------
pi + e = 5.85987448205
pi * e = 8.53973422267
sqrt(pi) + sqrt(e) = 3.42117512161
sqrt(pi + e) = 2.42071776175
sqrt(pi) - sqrt(e) = 0.123732580205
sqrt(pi - e) = 0.650623412683
sin(pi) = 1.22464679915e-16
cos(pi) = -1.0
tan(pi) = -1.22464679915e-16
log(e) = ln(e) = 1.0
lg(2) = log2(2) = 1.0
log10(1.0/10) = -1.0
pow(2, 10) = 1024.0
2**10 = 1024
2**100 = 1267650600228229401496703205376
2**1000 = 1071508607186267320948425049060001810561404811705533607443750388370351051
12493612249319837881569585812759467291755314682518714528569231404359845775746985748
0393456777482423098542107460506237114187795418215304647498358194126739876755916554
3946077062914571196477686542167660429831652624386837205668069376
len(str(2**100000)) = 30103


Posted by Scripter
,
다항식 p(x) 를 1차 다항식 ax - b 로 나눌 때의 몫과 나머지를 구하는 조립제법을
Python 언어로 구현해 보았다. 조립제법은 일명 Horner의 방법이라고도 불리우는데, 이는
x = a 에서 다항식 p(x)의 값 p(a)을 계산하는 가장 빠른 알고리즘이기도 하다.

         p(x) = (ax - b)q(x) + r

여기서 r은 나머지이며 r = p(b/a) 이다. 또 q(x)는 몫이다.

[참고]
    * 온라인으로 조립제법 표 만들기 손으로 계산하는 조립제법 표 
    * 온라인으로 구하는 다항식의 도함수: 조립제법을 이용한 다항식의 도함수


아래의 소스파일은 파일 testSyntheticDivision.py 를 수정한 것이다.

python 대신 jython이나 IronPython 으로도 수정 없이 그대로 실행된다.


  1. # coding: MS949
  2. #  Filename: testSyntheticDivision2.py
  3. #
  4. #  Purpose:  Find the quotient and remainder when some polynomial is
  5. #            divided by a monic polynomial of the first degree.
  6. #
  7. #  Execute:  python testSyntheticDivision2.py 5 -4 7 8 6 8
  8. #        Or  jython testSyntheticDivision2.py 5 -4 7 8 6 8
  9. import sys
  10. # 사용법 표시
  11. def printUsage():
  12.     print("사용법: python testSyntheticDivision2.py [제식의 계수] [피제식의 계수들]")
  13.     print("조립제법(synthetic method)에 의한 다항식 나눗셈 결과를 보여준다.")
  14. # 부동소수점수의 표현이 .0 으로 끝나는 경우 이를 잘라낸다.
  15. # 전체 문자열 표시 너비는 매개변수 width 로 전달받아 처리한다.
  16. def simplify(v, width=None):
  17.     t = "%g" % v
  18.     tlen = len(t)
  19.     if t[tlen-2:tlen-1] == ".0":
  20.         t = t[0, -2]
  21.     if width != None:
  22.         if tlen < width:
  23.             t = "              "[0: width - tlen] + t
  24.     return t
  25. # "/수" 표시하기
  26. # 부동소수점수의 표현이 .0 으로 끝나는 경우 이를 잘라낸다.
  27. # 전체 문자열 표시 너비는 매개변수 width 로 전달받아 처리한다.
  28. def simplifyReciprocal(v, width=None):
  29.     t = "/%g" % v
  30.     tlen = len(t)
  31.     if t[tlen-2:tlen-1] == ".0":
  32.         t = t[0, -2]
  33.     if width != None:
  34.         if tlen < width:
  35.             t = "              "[0: width - tlen] + t
  36.     return t
  37. # 다항식을 내림차순의 스트링 표현으로 반환
  38. def toPolyString(c):
  39.     t = ""
  40.     sc0 = simplify(c[0])
  41.     if len(c) > 2:
  42.         if sc0 == "1":
  43.             t += "x^%d" % (len(c)-1)
  44.         elif sc0 == "-1":
  45.             t += "-x^%d" % (len(c)-1)
  46.         else:
  47.             t += sc0 + " x^%d" % (len(c)-1)
  48.     elif len(c) == 2:
  49.         if sc0 == "1":
  50.             t += "x"
  51.         elif sc0 == "-1":
  52.             t += "-x"
  53.         else:
  54.             t += sc0 + " x"
  55.     elif len(c) == 1:
  56.         t += sc0
  57.     for i in range(1, len(c)):
  58.         k = len(c) - 1 - i
  59.         sc = simplify(c[i])
  60.         if k > 1:
  61.             if c[i] > 0.0:
  62.                 if sc == "1":
  63.                     t += " + " + "x^%d" % k
  64.                 else:
  65.                     t += " + " + sc + " x^%d" % k
  66.             elif c[i] < 0.0:
  67.                 if sc == "-1":
  68.                     t += " - " + "x^%d" % k
  69.                 else:
  70.                     t += " - " + simplify(abs(c[i])) + " x^%d" % k
  71.         elif k == 1:
  72.             if c[i] > 0.0:
  73.                 if sc == "1":
  74.                     t += " + " + "x"
  75.                 else:
  76.                     t += " + " + sc + " x"
  77.             elif c[i] < 0.0:
  78.                 if sc == "-1":
  79.                     t += " - " + "x"
  80.                 else:
  81.                     t += " - " + simplify(abs(c[i])) + " x"
  82.         elif k == 0:
  83.             if c[i] > 0.0:
  84.                 t += " + " + sc
  85.             elif c[i] < 0.0:
  86.                 t += " - " + simplify(abs(c[i]))
  87.     return t
  88. # 다항식 나눗셈 결과를
  89. #     (피제식) = (제식)(몫) + (나머지)
  90. # 형태로 출력
  91. def printDivisionResult(a, c, d, b):
  92.     strLine = "  " + toPolyString(c)
  93.     print( strLine )
  94.     strLine = "    = ( " + toPolyString( [a[0], -a[1]] ) + " )"
  95.     tmp = [0.0] * (len(b) - 1)
  96.     for i in range(0, len(tmp)):
  97.         tmp[i] = b[i]
  98.     strLine += "( " + toPolyString(tmp) + " )"
  99.     r = d[len(d) - 1]
  100.     if r > 0.0:
  101.         strLine += " + " + simplify(r)
  102.     elif r < 0.0:
  103.         strLine += " - " + simplify(abs(r))
  104.     print( strLine )
  105. # 조립제법 계산표 출력 함수
  106. def printSyntheticTable(a, c, s, d, q):
  107.     strLine = "         | "
  108.     strLine += simplify(c[0], 8)
  109.     for i in range(1, len(c)):
  110.         strLine += "  " + simplify(c[i], 8)
  111.     print( strLine )
  112.     strLine = simplify(a[1], 8) + " |"
  113.     strLine += "           "
  114.     strLine += simplify(s[1], 8)
  115.     for i in range(2, len(s)):
  116.         strLine += "  " + simplify(s[i], 8)
  117.     print( strLine )
  118.     strLine = "         |"
  119.     for i in range(0, len(q)):
  120.         strLine += "----------"
  121.     print( strLine )
  122.     strLine = "         | "
  123.     strLine += simplify(d[0], 8)
  124.     for i in range(1, len(d)):
  125.         strLine += "  " + simplify(d[i], 8)
  126.     print( strLine )
  127.     strLine = simplifyReciprocal(a[0], 8) + " | "
  128.     strLine += simplify(q[0], 8)
  129.     for i in range(1, len(q) - 1):
  130.         strLine += "  " + simplify(q[i], 8)
  131.     print( strLine )
  132. # 실행 시작 지점
  133. if len(sys.argv) < 3:
  134.     printUsage()
  135.     sys.exit(1)
  136. ######################################################
  137. # 피제식은 c_0 x^n +  c_1 x^(n -1) + ... + c_n
  138. # 제식은 a x -  b
  139. a = [float(sys.argv[1]), - float(sys.argv[2])]
  140. c = [0.0]*(len(sys.argv) - 3)
  141. s = [0.0]*(len(sys.argv) - 3)
  142. d = [0.0]*(len(sys.argv) - 3)
  143. b = [0.0]*(len(sys.argv) - 3)
  144. for i in range(0, len(c)):
  145.     c[i] = float(sys.argv[i + 3])
  146. ######################################################
  147. # 조립제법의 주요 부분
  148. s[0] = 0.0
  149. d[0] = c[0]
  150. b[0] = c[0] / a[0]
  151. for i in range(1, len(c)):
  152.     s[i] = b[i-1]*a[1]
  153.     d[i] = c[i] + s[i]
  154.     b[i] = d[i] / a[0]
  155. ######################################################
  156. # 몫의 계수와 나머지를 출력한다.
  157. print("몫의 계수는"),
  158. for i in range(0, len(b) - 2):
  159.     print(simplify(b[i], None) + ", " ),
  160. print(simplify(b[len(b) - 2], None)),
  161. print("이고, 나머지는 " + simplify(d[len(d) - 1], None) + " 이다.")
  162. print
  163. ######################################################
  164. # 조립제법 표를 출력한다.
  165. printSyntheticTable(a, c, s, d, b)
  166. print
  167. ######################################################
  168. # (피제식) = (제식) x (몫) + (나머지)
  169. printDivisionResult(a, c, d, b)




실행> python testSyntheticDivision2.py 5 -4 7 8 6 8
몫의 계수는 1.4,  2.72,  3.376 이고, 나머지는 21.504 이다.

         |        7         8         6         8
       4 |                5.6     10.88    13.504
         |----------------------------------------
         |        7      13.6     16.88    21.504
      /5 |      1.4      2.72     3.376

  7 x^3 + 8 x^2 + 6 x + 8
    = ( 5 x - 4 )( 1.4 x^2 + 2.72 x + 3.376 ) + 21.504



Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

Python 언어로 숫자 맞추기 게임을 작성해 보았다.
input()  함수가 내부적으로 Python 2.x와 Python3.x에서 다르게 동작한다.

    In Python2.*, input([prompt]) was equivalent to eval(raw_input([prompt])).
    In Python3.*, input([prompt]) of Python2.* was removed and raw_input([prompt])
                        was renamed as input([prompt]).

아래 소스의 16째 줄 guess = int(sbuf) 는 스트링을 정수로 타입변환하는 과정이다.



소스 파일명: guessNumber01.py

  1. #!/usr/bin/env python
  2. #
  3. #   Filename: guessNumber01.py
  4. #   Purpose:  Interatice game guessing a given number.
  5. #                 if CONDITION:
  6. #                     ......
  7. #                 else:
  8. #                     ......
  9. #   Execute: python guessNumber01.py
  10. def doGuessing(num):
  11.     print("Enter your guess:")
  12.     #sbuf = raw_input()     # for Python 2.x
  13.     sbuf = input()          # for Python 3.x
  14.     guess = int(sbuf)
  15.     if guess == num:
  16.         print("You win!")
  17.         return
  18.     # we won't get here if guess == num
  19.     if guess < num:
  20.         print("Too low!")
  21.         doGuessing(num)
  22.     else:
  23.         print("Too high!")
  24.         doGuessing(num)
  25. doGuessing(123)




실행> python guessNumber01.py
Enter your guess:
111
Too low!
Enter your guess:
222
Too high!
Enter your guess:
123
You win!



위의 소스는 Jython 2.2.1이나 Jython 2.5.1로 실행해도 똑같이 실행된다.

실행> jython guessNumber01.py
Enter your guess:
111
Too low!
Enter your guess:
222
Too high!
Enter your guess:
123
You win!




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.



Posted by Scripter
,
In Python2.*, input([prompt]) was equivalent to eval(raw_input([prompt])).

In Python3.*, input([prompt]) of Python2.* was removed and raw_input([prompt]) was renamed as input([[rompt]).


* Python 2.6에서 input() 함수 테스트하기

명령행프롬프트> python
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "icense" for more information.
>>> x = input("Input a number: ")
Input a number: aaa
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'aaa' is not defined


* Python 3.1에서 input() 함수 테스트하기

명령행프롬프트> python
Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> x = input("Input a number: ")
Input a number: aaa
>>> print x
  File "<stdin>", line 1
    print x
          ^
SyntaxError: invalid syntax
>>> print(x)
aaa
>>> type(x)
<class 'str'>
Posted by Scripter
,


[파일명:  testStringFindInList.py]------------------------------------------------
# coding=ms949

import sys

def find(arr, s):
    for i in range(0, len(arr)):
     if arr[i].find(s) >= 0:
      return i
    return -1;

def printArray(arr):
    sys.stdout.write("[")
    for i in range(0, len(arr) - 1):
         sys.stdout.write(arr[i] + ", ")
    if len(arr) > 0:
        sys.stdout.write(arr[len(arr) - 1])
    print("]")

words = ["하나", "둘", "셋", "넷", "다섯", "여섯"]

sys.stdout.write("list: ")
printArray(words)
where = find(words, "셋")
if where > 0:
    sys.stdout.write("발견!  ")
    print("Next word of 셋 in list: " + words[where+1])

print("Sorting...")
words.sort()

sys.stdout.write("list: ")
printArray(words)
where = find(words, "셋")
if where > 0:
    sys.stdout.write("발견!  ")
    print("Next word of 셋 in list: " + words[where+1])
------------------------------------------------


실행> python testStringFindInList.py
list: [하나, 둘, 셋, 넷, 다섯, 여섯]
발견!  Next word of 셋 in list: 넷
Sorting...
list: [넷, 다섯, 둘, 셋, 여섯, 하나]
발견!  Next word of 셋 in list: 여섯



크리에이티브 커먼즈 라이선스
Creative Commons License

Posted by Scripter
,


[파일명:  testSort.py]------------------------------------------------
import sys

def printArray(a):
    sys.stdout.write("[")
    for i in range(0, len(a) - 1):
        sys.stdout.write("%s, " % a[i])
    if len(a) > 0:
        sys.stdout.write("%s" % a[-1])
    sys.stdout.write("]\n")

list = sys.argv[1::]
list.sort()
printArray(list)
------------------------------------------------


실행> python testSort.py one two three four five
[five, four, one, three, two]

실행> python testSort.py 하나 둘 셋 넷 다섯
[넷, 다섯, 둘, 셋, 하나]


IronPython으로 실행하기:
실행> ipy testSort.py one two three four five
[five, four, one, three, two]

실행> ipy testSort.py 하나 둘 셋 넷 다섯
[넷, 다섯, 둘, 셋, 하나]


Jython으로 실행하기:
실행> jython testSort.py one two three four five
[five, four, one, three, two]

( Jython으로 실행하는 경우, )
( 버전 2.2.1이든 2.5b3이든 명령행 옵션으로 넣어준 한글을 잘 처리하지 못한다. )
실행> jython testSort.py 하나 둘 셋 넷 다섯
[?, ??, ?, ?, ??]


 

크리에이티브 커먼즈 라이선스
Creative Commons License

 

Posted by Scripter
,