초등학교 때 배우는 두 정수의 곱셈표를 만들어 주는 Python 소스이다.
(이 소스는 Jython이나 IronPython에서도 수정없이 그대로 실행된다.)

이항 연산자 // 는 Python의 정수나눗셈 연산자이다.


# Filename: makeMultTable.py
#
#     Print a multiplication table.
#
#     Execute: python makeMultTable.py 230 5100
#
# Date: 2009/03/06
#
#

import sys

def printUsing():
    print "Using: python makeMultTable.py [number1] [number2]"
    print "Print a multiplication table for the given two integers."

def printMultTable(x, y):
    nx = x
    if nx < 0:
        nx = -nx
    ny = y
    if ny < 0:
        ny = -ny
    ntail1 = 0
    ntail2 = 0
    while nx % 10 == 0:
        nx = nx // 10
        ntail1 = ntail1 + 1
    while ny % 10 == 0:
        ny = ny // 10
        ntail2 = ntail2 + 1
    z = nx * ny
    strZ = "%d" % z
    strX = "%d" % nx
    strY = "%d" % ny
    n = len(strY)
    zeros  = "0000000000000000000000000000000000000000"
    whites = "                                        "
    bars   = "----------------------------------------"
    loffset = "       "
    line4 = loffset + strZ
    line1 = loffset + whites[0: len(strZ) - len(strX)] + strX
    line2 = "   x ) " +  whites[0: len(strZ) - len(strY)] + strY
    line3 = "     --" +  bars[0: len(strZ)]
    print line1 + zeros[0: ntail1]
    print line2 + zeros[0: ntail2]
    print line3
    if len(strY) > 1:
        for i in range(0, len(strY)):
            y1 = int(strY[len(strY) - i - 1: len(strY) - i])
            if y1 != 0:
                strT = "%d" % (nx * y1)
                print loffset + whites[0: len(strZ) - len(strT) - i] + strT
        print line3
    print line4 + zeros[0: ntail1] + zeros[0: ntail2]

if len(sys.argv) >= 3:
    x = long(sys.argv[1])
    y = long(sys.argv[2])
    print
    printMultTable(x, y)
else:
    printUsing()



실행> python makeMultTable.py 230 5100
결과>

         230
   x )   5100
     ------
         23
       115
     ------
       1173000

 

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

 

Posted by Scripter
,