다음은  이차방정식 x^2 - x - 1  = 0 의 양의 근 즉 황금비율(golden ratio)을 구하는 Python 애플리케이션 소스이다. 황금비율을 구하는 비례방정식은   1 : x = x : (x+1) 이며, 이를 이차방정식으로 표현한 것이 x^2 - x - 1  = 0 이다.

See:  http://en.wikipedia.org/wiki/Golden_ratio


  1. # -*- encoding: ms949 -*-
  2. #  Filename: testGoldenRatio.py
  3. #    황금률(즉, 이차방정식 x^2 - x - 1  = 0 의 양의 근)을 계산한다.
  4. #
  5. #   Execute: python testGoldenRatio.py
  6. #
  7. #      Date:  2008/03/24
  8. #    Author: PH Kim   [ pkim (AT) scripts.pe.kr ]
  9. import sys
  10. import math
  11. def printUsing():
  12.     print("Using: python testGoldenRatio.py [-h|-help]")
  13.     print("This calculates the value of the golden ratio.")
  14. # 이차방정식 a x^2 + b x + c  = 0 의 근을 구한다.
  15. def findQuadraticRoot(a, b, c):
  16.     if a == 0.0:
  17.         raise RuntimeError("Since the highest coefficient is zero, the given equation is not a quadratic equation.")
  18.     elif b*b - 4*a*c < 0.0:
  19.         raise RuntimeError("Since the discriminant " + (b*b - 4*a*c) + " is negative, the given equation has no real root.")
  20.     x1 = (-b + math.sqrt(b*b - 4*a*c)) / (2.0 * a)
  21.     x2 = (-b - math.sqrt(b*b - 4*a*c)) / (2.0 * a)
  22.     return [x1, x2]
  23. # 실행 시작 지점
  24. if len(sys.argv) > 1 and (sys.argv[1] == "-h" or sys.argv[1] == "-help"):
  25.     printUsing()
  26.     sys.exit(1)
  27. values = findQuadraticRoot(1.0, -1.0, -1.0)
  28. x1 = values[0]
  29. x2 = values[1]
  30. if x1 >= x2:
  31.     print("The bigger root is " + str(x1) + ", ")
  32.     print("and the less root is " + str(x2) + ".")
  33. else:
  34.     print("The bigger root is " + str(x2) + ", ")
  35.     print("and the less root is " + str(x1) + ".")



실행> python testGoldenRatio.py
The bigger root is 1.61803398875,
and the less root is -0.61803398875.


실행> jython testGoldenRatio.py
The bigger root is 1.618033988749895,
and the less root is -0.6180339887498949.



위의 소스 코드에서 인코딩 선언 부분만

# -*- encoding: cp949 -*-

로 고치면, IronPython에서도 실행된다.


실행> ipy testGoldenRatio.py
The bigger root is 1.61803398875,
and the less root is -0.61803398875.


만일 Jython 2.5.0 이상이면
LookupError: unknown encoding 'ms949'
또는
SyntaxError: Unknown encoding: ms949
와 같은 에러를 만날 수 있다. 이럴 때는

# -*- encoding: iso-8859-1 -*-
또는
# coding: iso-8859-1

로 해야할 것이다. (이는 Jython 2.5.x 의 버그인 것으로 보인다.)



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

Posted by Scripter
,
현재 시각을 컨솔에 보여주는 간단한 애플리케이션의 Python 언어 소스 코드이다.
UTC란 1970년 1월 1일 0시 0분 0초를 기준으로 하여 경과된 초 단위의 총 시간을 의미한다.
* UTC(Universal Time  Coordinated, 협정세계시, 協定世界時)


  1. # -*- encoding: ms949 -*-
  2. #  Filename: testCTime.py
  3. #  Execute: python testCTime.py
  4. from time import *
  5. # Python case
  6. weekNames = [ "월", "화", "수", "목", "금", "토", "일" ]  
  7. utctime = time()
  8. cNow = localtime(utctime)
  9. # 1970년 1월 1일 0시 0분 0초부터 시작하여 현재까지의 초
  10. print("UTC: %d초" % int(utctime))
  11. # 현재 시각 표시: 200x년 x월 xx일 (x요일) xx시 xx분 xx초
  12. print("%d년 %d월 %d일 (%s요일) %d시 %d분 %d초" % (cNow.tm_year, cNow.tm_mon, cNow.tm_mday, weekNames[cNow.tm_wday], cNow.tm_hour, cNow.tm_min, cNow.tm_sec) )
  13. # 1월 1일은 1, 1월 2일은 2
  14. # localtime().tz_isdat == 0 이면, 서머타임 없음
  15. # localtime().tz_isdat == 1 이면, 서머타임 있음
  16. if cNow.tm_isdst == 0:
  17.     strIsDST = "안함"
  18. else:
  19.     strIsDST = "함"
  20. print("올해 몇 번째 날: %d, 서머타임 적용 여부: %s" % (cNow.tm_yday, strIsDST))



실행> python testCTime.py
UTC: 1206324568
2008년 3월 24일 (월요일) 11시 9분 28초
올해 몇 번째 날: 84, 서머타임 적용 여부: 안함


실행> jython testCTime.py
UTC: 1206324572
2008년 3월 24일 (월요일) 11시 9분 32초
올해 몇 번째 날: 84, 서머타임 적용 여부: 안함



다음은 IronPython을 위해 새로 작성된 소스 코드이다.
인코딩에 ms949와 MS949는 에러가 생기고, cp949, CP949, euc-kr, EUC-KR 만 인식된다. 
날짜와 시간 관련 처리는 닷넷(C#)의 것을 따랐다.

  1. # -*- encoding: cp949 -*-
  2. #  Filename: testCTime.py
  3. #  Execute: ipy testCTime.py
  4. from System import *
  5. # Python/Jython/IronPython case
  6. weekNames = [ "월", "화", "수", "목", "금", "토", "일" ]  
  7. cNow = DateTime.Now
  8. StartOfEpoch = DateTime(1970, 1, 1)
  9. # 1970년 1월 1일 0시 0분 0초부터 시작하여 현재까지의 초
  10. print "UTC: %d초" % (Convert.ToInt64((DateTime.UtcNow - StartOfEpoch).TotalMilliseconds)/1000L)
  11. # 현재 시각 표시: 200x년 x월 xx일 (x요일) xx시 xx분 xx초
  12. print("%d년 %d월 %d일 (%s요일) %d시 %d분 %d초" % (cNow.Year, cNow.Month, cNow.Day, weekNames[int(cNow.DayOfWeek)], cNow.Hour, cNow.Minute, cNow.Second) )
  13. # cNow.IsDaylightSavingTime() == False 이면, 서머타임 없음
  14. # cNow.IsDaylightSavingTime() == True 이면, 서머타임 있음
  15. if cNow.IsDaylightSavingTime():
  16.     strIsDST = "함"
  17. else:
  18.     strIsDST = "안함"
  19. print("올해 몇 번째 날: %d , 서머타임 적용 여부: %s" % (cNow.DayOfYear, strIsDST))



실행> ipy testCTime.py
UTC: 1239235489초
2009년 4월 9일 (금요일) 9시 4분 49초
올해 몇 번째 날: 99 , 서머타임 적용 여부: 안함



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

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

         p(x) = (x - a)q(x) + r

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

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


아래의 소스파일은 Groovy용 소스파일 testSyntheticDivision.groovy 를 Python용으로 수정한 것이다.

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


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




실행> python testSyntheticDivision.py 1 2 3 4 5
몫의 계수는 2, 5, 9 이고, 나머지는 14 이다.

       |      2       3       4       5
     1 |              2       5       9
       |---------------------------------
              2       5       9      14

  2 x^3 + 3 x^2 + 4 x + 5
    = ( x - 1 )( 2 x^2 + 5 x + 9 ) + 14



Posted by Scripter
,

다음은 Groovy용 소스파일 testForFor.groovy를 Python용으로 수정한 것이다.
Python 언어에서 print 문은 Groovy 언어의 println 문 처럼 개행(newline) 문자를 포함하여 출력한다.

Groovy 언어와 Java 언어에서 쓰이는 조건 분기 구문

        if (조건식1) {
            블럭1
        }
        else if (조건식2) {
            블럭2
        }
        else if (조건식3) {
            블럭3
        }
        else {
            블럭4
        }

에 해딩하는 Python 언어의 구문은

        if 조건식1:
            블럭1
        elif 조건식2:
            블럭2
        elif 조건식3:
            블럭3
        else:
            블럭4

이다.

또 아래의 소스의 첫 줄에 적힌

        # coding:euc-kr



        # -*- encoding: euc-kr -*-

로 해도 된다. (이는 소스 중에 들어간 한글 문자 때문이다.)




  1. # coding:euc-kr
  2. #
  3. #  Filename: testForFor.py
  4. #
  5. #  Execute:  python testForFor.py
  6. #        Or  jython testForFor.py
  7. #
  8. #  Date:  2008. 3. 3
  9. def getDan(dan):
  10.     t = [""]*19
  11.     for j in range(0,  19):
  12.         sa = "%s" % dan
  13.         if len(sa) < 2:
  14.             sa = " %s" % dan
  15.         sb = "%s" % (j + 1)
  16.         if len(sb) < 2:
  17.             sb = " %s" % (j + 1)
  18.         sval = "%s" % (dan*(j + 1))
  19.         if len(sval) < 2:
  20.             sval = "  %s" % (dan*(j + 1))
  21.         elif len(sval) < 3:
  22.             sval = " %s" % (dan*(j + 1))
  23.         t[j] = sa + " x " + sb + " = " + sval
  24.     return t
  25. # 19단표를 모두 80컬럼 컨솔에 출력한다.
  26. def printAllNineteenDan():
  27.     arr = [[""]*18]*19
  28.     for i in range(2, 20):
  29.         arr[i - 2] = getDan(i)
  30.     # Python 소스 코드에서도 배열 대신 리스트를 사용한다.
  31.     d = [ 2, 7, 11, 16 ]      # 각 줄단위 블럭의 첫단
  32.     counter = [ 5, 4, 5, 4 ]  # 각 줄단위 블럭에 속한 단의 개수
  33.     lines = [""]*19
  34.     for k in range(0, len(d)):
  35.         # 8-바이트 길이의 한 줄씩 완성
  36.         for i in range(0, 19):
  37.             lines[i] = arr[d[k]-2][i]
  38.             for j in range(1, counter[k]):
  39.                 lines[i] += "   " +  arr[d[k]-2+j][i]
  40.         # 80 바이트 길이의 한 줄씩 출력
  41.         for i in range(0, 19):
  42.             print lines[i]
  43.         print
  44. printAllNineteenDan()


실행> python testForFor.py 
또는   jython testForFor.py
또는   ipy testForFor.py

 2 x  1 =   2    3 x  1 =   3    4 x  1 =   4    5 x  1 =   5    6 x  1 =   6
 2 x  2 =   4    3 x  2 =   6    4 x  2 =   8    5 x  2 =  10    6 x  2 =  12
 2 x  3 =   6    3 x  3 =   9    4 x  3 =  12    5 x  3 =  15    6 x  3 =  18
 2 x  4 =   8    3 x  4 =  12    4 x  4 =  16    5 x  4 =  20    6 x  4 =  24
 2 x  5 =  10    3 x  5 =  15    4 x  5 =  20    5 x  5 =  25    6 x  5 =  30
 2 x  6 =  12    3 x  6 =  18    4 x  6 =  24    5 x  6 =  30    6 x  6 =  36
 2 x  7 =  14    3 x  7 =  21    4 x  7 =  28    5 x  7 =  35    6 x  7 =  42
 2 x  8 =  16    3 x  8 =  24    4 x  8 =  32    5 x  8 =  40    6 x  8 =  48
 2 x  9 =  18    3 x  9 =  27    4 x  9 =  36    5 x  9 =  45    6 x  9 =  54
 2 x 10 =  20    3 x 10 =  30    4 x 10 =  40    5 x 10 =  50    6 x 10 =  60
 2 x 11 =  22    3 x 11 =  33    4 x 11 =  44    5 x 11 =  55    6 x 11 =  66
 2 x 12 =  24    3 x 12 =  36    4 x 12 =  48    5 x 12 =  60    6 x 12 =  72
 2 x 13 =  26    3 x 13 =  39    4 x 13 =  52    5 x 13 =  65    6 x 13 =  78
 2 x 14 =  28    3 x 14 =  42    4 x 14 =  56    5 x 14 =  70    6 x 14 =  84
 2 x 15 =  30    3 x 15 =  45    4 x 15 =  60    5 x 15 =  75    6 x 15 =  90
 2 x 16 =  32    3 x 16 =  48    4 x 16 =  64    5 x 16 =  80    6 x 16 =  96
 2 x 17 =  34    3 x 17 =  51    4 x 17 =  68    5 x 17 =  85    6 x 17 = 102
 2 x 18 =  36    3 x 18 =  54    4 x 18 =  72    5 x 18 =  90    6 x 18 = 108
 2 x 19 =  38    3 x 19 =  57    4 x 19 =  76    5 x 19 =  95    6 x 19 = 114

 7 x  1 =   7    8 x  1 =   8    9 x  1 =   9   10 x  1 =  10
 7 x  2 =  14    8 x  2 =  16    9 x  2 =  18   10 x  2 =  20
 7 x  3 =  21    8 x  3 =  24    9 x  3 =  27   10 x  3 =  30
 7 x  4 =  28    8 x  4 =  32    9 x  4 =  36   10 x  4 =  40
 7 x  5 =  35    8 x  5 =  40    9 x  5 =  45   10 x  5 =  50
 7 x  6 =  42    8 x  6 =  48    9 x  6 =  54   10 x  6 =  60
 7 x  7 =  49    8 x  7 =  56    9 x  7 =  63   10 x  7 =  70
 7 x  8 =  56    8 x  8 =  64    9 x  8 =  72   10 x  8 =  80
 7 x  9 =  63    8 x  9 =  72    9 x  9 =  81   10 x  9 =  90
 7 x 10 =  70    8 x 10 =  80    9 x 10 =  90   10 x 10 = 100
 7 x 11 =  77    8 x 11 =  88    9 x 11 =  99   10 x 11 = 110
 7 x 12 =  84    8 x 12 =  96    9 x 12 = 108   10 x 12 = 120
 7 x 13 =  91    8 x 13 = 104    9 x 13 = 117   10 x 13 = 130
 7 x 14 =  98    8 x 14 = 112    9 x 14 = 126   10 x 14 = 140
 7 x 15 = 105    8 x 15 = 120    9 x 15 = 135   10 x 15 = 150
 7 x 16 = 112    8 x 16 = 128    9 x 16 = 144   10 x 16 = 160
 7 x 17 = 119    8 x 17 = 136    9 x 17 = 153   10 x 17 = 170
 7 x 18 = 126    8 x 18 = 144    9 x 18 = 162   10 x 18 = 180
 7 x 19 = 133    8 x 19 = 152    9 x 19 = 171   10 x 19 = 190

11 x  1 =  11   12 x  1 =  12   13 x  1 =  13   14 x  1 =  14   15 x  1 =  15
11 x  2 =  22   12 x  2 =  24   13 x  2 =  26   14 x  2 =  28   15 x  2 =  30
11 x  3 =  33   12 x  3 =  36   13 x  3 =  39   14 x  3 =  42   15 x  3 =  45
11 x  4 =  44   12 x  4 =  48   13 x  4 =  52   14 x  4 =  56   15 x  4 =  60
11 x  5 =  55   12 x  5 =  60   13 x  5 =  65   14 x  5 =  70   15 x  5 =  75
11 x  6 =  66   12 x  6 =  72   13 x  6 =  78   14 x  6 =  84   15 x  6 =  90
11 x  7 =  77   12 x  7 =  84   13 x  7 =  91   14 x  7 =  98   15 x  7 = 105
11 x  8 =  88   12 x  8 =  96   13 x  8 = 104   14 x  8 = 112   15 x  8 = 120
11 x  9 =  99   12 x  9 = 108   13 x  9 = 117   14 x  9 = 126   15 x  9 = 135
11 x 10 = 110   12 x 10 = 120   13 x 10 = 130   14 x 10 = 140   15 x 10 = 150
11 x 11 = 121   12 x 11 = 132   13 x 11 = 143   14 x 11 = 154   15 x 11 = 165
11 x 12 = 132   12 x 12 = 144   13 x 12 = 156   14 x 12 = 168   15 x 12 = 180
11 x 13 = 143   12 x 13 = 156   13 x 13 = 169   14 x 13 = 182   15 x 13 = 195
11 x 14 = 154   12 x 14 = 168   13 x 14 = 182   14 x 14 = 196   15 x 14 = 210
11 x 15 = 165   12 x 15 = 180   13 x 15 = 195   14 x 15 = 210   15 x 15 = 225
11 x 16 = 176   12 x 16 = 192   13 x 16 = 208   14 x 16 = 224   15 x 16 = 240
11 x 17 = 187   12 x 17 = 204   13 x 17 = 221   14 x 17 = 238   15 x 17 = 255
11 x 18 = 198   12 x 18 = 216   13 x 18 = 234   14 x 18 = 252   15 x 18 = 270
11 x 19 = 209   12 x 19 = 228   13 x 19 = 247   14 x 19 = 266   15 x 19 = 285

16 x  1 =  16   17 x  1 =  17   18 x  1 =  18   19 x  1 =  19
16 x  2 =  32   17 x  2 =  34   18 x  2 =  36   19 x  2 =  38
16 x  3 =  48   17 x  3 =  51   18 x  3 =  54   19 x  3 =  57
16 x  4 =  64   17 x  4 =  68   18 x  4 =  72   19 x  4 =  76
16 x  5 =  80   17 x  5 =  85   18 x  5 =  90   19 x  5 =  95
16 x  6 =  96   17 x  6 = 102   18 x  6 = 108   19 x  6 = 114
16 x  7 = 112   17 x  7 = 119   18 x  7 = 126   19 x  7 = 133
16 x  8 = 128   17 x  8 = 136   18 x  8 = 144   19 x  8 = 152
16 x  9 = 144   17 x  9 = 153   18 x  9 = 162   19 x  9 = 171
16 x 10 = 160   17 x 10 = 170   18 x 10 = 180   19 x 10 = 190
16 x 11 = 176   17 x 11 = 187   18 x 11 = 198   19 x 11 = 209
16 x 12 = 192   17 x 12 = 204   18 x 12 = 216   19 x 12 = 228
16 x 13 = 208   17 x 13 = 221   18 x 13 = 234   19 x 13 = 247
16 x 14 = 224   17 x 14 = 238   18 x 14 = 252   19 x 14 = 266
16 x 15 = 240   17 x 15 = 255   18 x 15 = 270   19 x 15 = 285
16 x 16 = 256   17 x 16 = 272   18 x 16 = 288   19 x 16 = 304
16 x 17 = 272   17 x 17 = 289   18 x 17 = 306   19 x 17 = 323
16 x 18 = 288   17 x 18 = 306   18 x 18 = 324   19 x 18 = 342
16 x 19 = 304   17 x 19 = 323   18 x 19 = 342   19 x 19 = 361


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

소스 파일명: testWhile.py

  1. # coding=euc-kr
  2. #  Filename: testWhile.py
  3. #
  4. #  Purpose:  Example using the while loop syntax
  5. #                while ....
  6. #
  7. # Execute: python testWhile.py -200 300
  8. #
  9. import sys
  10. # 사용법 표시
  11. def printUsage():
  12.     print "Using: python testWhile.py [integer1] [integer2]"
  13.     print "This finds the greatest common divisor of the given two integers."
  14. if len(sys.argv) != 3:
  15.     printUsage()
  16.     sys.exit(1)
  17. # --------------------------------------
  18. # 명령행 인자의 두 스트링을 가져와서
  19. # 정수 타입으로 변환하여
  20. # 변수 val1과 val2에 저장한다.
  21. val1 = long(sys.argv[1])
  22. val2 = long(sys.argv[2])
  23. # a는 |val1|, |val2| 중 큰 값
  24. a = abs(val1)
  25. b = abs(val2)
  26. if a < b:
  27.     a = abs(val2)
  28.     b = abs(val1)
  29. if b == 0:
  30.     print "GCD(%d, %d) = %d" % (val1, val2, a)
  31.     sys.exit(0)
  32. # --------------------------------------
  33. # Euclidean 알고리즘의 시작
  34. #
  35. # a를 b로 나누어 몫은 q에, 나머지는 r에 저장
  36. q = a / b
  37. r = a % b
  38. # --------------------------------------
  39. # Euclidean 알고리즘의 반복 (나머지 r이 0이 될 때 까지)
  40. while r != 0:
  41.     a = b
  42.     b = r
  43.     q = a / b
  44.     r = a % b
  45. # 나머지가 0이면 그 때 나눈 수(제수) b가 최대공약수(GCD)이다.
  46. gcd = b
  47. # 최대공약수(GCD)를 출력한다.
  48. print "GCD(%d, %d) = %d" % (val1, val2, gcd)


실행:

Command> python testWhile.py
Using: python testWhile.py [integer1] [integer2]
This finds the greatest common divisor of the given two integers.

Command> python testWhile.py -200 300
GCD(-200, 300) = 100

Command> python testWhile.py -200 0
GCD(-200, 0) = 200

Command> python testWhile.py 125 100
GCD(125, 100) = 25

Command> python testWhile.py 23 25
GCD(23, 25) = 1


위의 소스 코드는 ipy 명령에 의하여 IronPython에서도 수정 없이 그대로 실행된다.




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

Posted by Scripter
,

소스 파일명: testIf.py

  1. # coding=euc-kr
  2. """
  3.    Filename: testIf.py
  4.    Purpose:  Example using the conditional control structure syntax
  5.                  if .... else ...
  6.    Execute: python testIf.py [number]
  7. """
  8. import sys    # sys.argv를 위한 수입(import) 구문
  9. # 사용법을 보여주는 함수
  10. def printUsing():
  11.    print("Using: python testIf.py [number]")
  12.    print("This determines whether the number is positive or not.")
  13. # 명령행 인자의 개수가 1이 아니면 사용법을 보여준다.
  14. if len(sys.argv) != 2:
  15.     printUsing()
  16.     sys.exit(1)
  17. # 명령행 인자의 스트링을 가져와서
  18. # 배정밀도 부동소수점수로 변환하여
  19. # 변수 val에 저장한다.
  20. val = float(sys.argv[1])
  21. # 변수 val에 저장된 값이 양수인지 음수인지 0인지를
  22. # 판단하는 if...else... 조건문
  23. if val > 0.0:
  24.     print("%g is a positive number." % val)
  25. elif val < 0.0:
  26.     print("%g is a negative number." % val)
  27. else:
  28.     print("%g is zero." % val)


실행> python testIf.py
Using: python testIf.py [number]
This determines whether the number is positive or not.

실행> python testIf.py 6.25
6.25 is a positive number.

실행> python testIf.py -6.25
-6.25 is a negative number.

실행> python testIf.py 0
0 is zero.


※ 위의 소스 코드는 Jython으로도 수정 없이 그대로 실행된다.

실행> jython testIf.py
Using: python testIf.py [number]
This determines whether the number is positive or not.

실행> jython testIf.py 1.02
1.02 is a positive number.

실행> jython testIf.py -1.02
-1.02 is a negative number.

실행> jython testIf.py 0
0 is zero.


위의 소스 코드는 ipy 명령에 의하여 IronPython에서도 수정 없이 그대로 실행된다.




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

Posted by Scripter
,

Python 언어에서 명령행 인자는 sys.argv 라는 변수로 처리한다.
sys.argv는 모듈 sys에 속하는 변수 argv를 의미하며, 이는 명령행 실행시 옵션으로 입력된 인자들을 스트링 값으로 모아둔 리스트형의 변수이다.
모듈 sys을 하기 위해서는

        import sys

라는 수입(import) 구문을 소스 선두 부분에 적어주어야 한다.

C/C++/Java/Ruby 언어들과는 달리 리스트의 0번의 값(즉 sys.argv[0])은 python 명령 바로 다음에 입력된 (실행될) Python 소스파일명을 가리키므로, 1번부터 처리해야 한다. 즉 Python 언어에서 sys.argv[1], sys.argv[2], sys.argv[3], ... 들이 각각 C 언어의 argv[0], argv[1], argv[2], .... 들에 해당하며, Java 언어의 args[0], args[1], args[2], ... 들에 해당한다.

다음 소스의 앞 부분에

    #! /usr/bin/python
    # -*- encoding: euc-kr -*-

를 적어둔 것은 소스 코드에서 (주석문에) ASCII 가 아닌 문자(여기서는 한글 euc-kr)를 소스 코드에서 사용하고 있기 때문이다. 이 두 줄은

    #! /usr/bin/python
    # coding: euc-kr

으로 하여도 된다. 만일 소스 코드 파일을 utf-8 인코딩으로 저장하였다면 euc-kr 대신 utf-8로 하여야 할 것이다. (참고로, Ubuntu 플랫폼에서는 소스파일 저장시 반드시 utf-8 인코딩으로 저장하여야 한다.)


소스파일명: testArguments.py

  1. #!/usr/bin/python
  2. # -*- encoding: euc-kr -*-
  3. import sys
  4. # 명령행 인자(command-line argument) 개수 출력
  5. print "Count of arguments: %d" % (len(sys.argv)-1)
  6. sum = 0.0
  7. for i in range(1, len(sys.argv)):
  8.     # 스트링을 부동소수점수로 변환하여 누적
  9.     sum += float(sys.argv[i])
  10. # 누적된 값을 출력
  11. print "The sum of arguments is %g" % sum


실행> python testArguments.py 1 2 3 4
Count of arguments: 4
The sum of arguments is 10


실행> python testArguments.py 1 2 3 4.1
Count of arguments: 4
The sum of arguments is 10.1


※ 위의 소스 코드는 Jython으로도 수정 없이 그대로 실행된다.

실행> jython testArguments.py 1 2 3 4
Count of arguments: 4
The sum of arguments is 10


실행> jython testArguments.py 1 2 3 4.1
Count of arguments: 4
The sum of arguments is 10.1


※ 위의 소스 코드는 IronPython으로도 수정 없이 그대로 실행된다.

실행> ipy testArguments.py 1 2 3 4
Count of arguments: 4
The sum of arguments is 10


실행> ipy testArguments.py 1 2 3 4.1
Count of arguments: 4
The sum of arguments is 10.1




Posted by Scripter
,

Python(및 Jython) 언어의 함수 정의 구문 양식은

       def functionName(parameters):
             block

이다.

또 Python(및 Jython) 언어의 반복문 양식은

       for varName in Range:
             block

이다.



소스 파일명: forTest.py
------------------------------[소스 시작]
def printDan(dan):
  for i in range(1, 10):
    print "%d x %d = %d" % (dan, i, dan*i)

printDan(2)
------------------------------[소스 끝]

실행> python forTest.py      (또는 jython forTest.py)
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18

* Jython의 경우:
실행> jython forTest.py
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18


* IronPython의 경우:
실행> ipy forTest.py
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18





Posted by Scripter
,
컨솔에 문자 출력하는 python 구문은

       print "문자열(스트링)"

이다. 여기서 개행문자 "\n"은 추가하지 않아도 된다.
(Jython의 문자 출력 구문도 위와 같다.)
 
소스 파일명: hello.py
------------------------------[소스 시작]
print "Hello, world!"
------------------------------[소스 끝]

실행> python hello.py
Hello, world!


* Jython으로 실행하는 경우:

실행> jython hello.py
Hello, world!


* IronPython으로 실행하는 경우:

실행> ipy hello.py
Hello, world!

Posted by Scripter
,