다음은  대화형 모드(interactive mode)에서 진법 변환(radix conversion)하는 Python 소스 코드이다.
메뉴는 주메뉴 Command: (S)et radix, (A)bout, (Q)uit or E(x)it
와 부메뉴 SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
로 구성되어 있으며, 진법 변환의 핵심은 Python의 빌트인 함수 int(string, radix)와 소스 코드에 자체 작성된 함수 itoa(number, radix)의 사용이다.

         val = int(s, srcRdx)
         ret = itoa(val, destRdx)

지원되는 진법은 2진법에서 36진법까지이다.
(Jython으로는 finally: 구문 때문에 실행이 안된다.)



  1. #  Filename: convertRadix.py
  2. #            Convert radix in a interactive mode.
  3. #
  4. #  Execute: python convertRadix.py
  5. #
  6. #      Date:  2008/03/25
  7. #    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  8. import sys
  9. def println(s=None):
  10.     if s != None:
  11.         print(s)
  12.     else:
  13.         print
  14. def printUsage():
  15.     println("Usage: python convertRadix.py")
  16.     println("Convert radix in a interactive mode, where the maximum radix is 36.")
  17. def printAbout():
  18.     println("    About: Convert radix in a interactive mode.")
  19. def printMainMenu():
  20.     println("  Command: (S)et radix, (A)bout, (Q)uit or E(x)it")
  21. def printMainPrompt():
  22.     print("  Prompt>"),
  23. def printSubMenu(srcRadix, destRadix):
  24.     println("    Convert Radix_" + str(srcRadix) + " to Radix_" + str(destRadix))
  25.     println("    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit")
  26. def printSubPrompt():
  27.     print("    Input Value>>"),
  28. BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  29. def itoa(num, radix=10):
  30.    isNegative = False
  31.    if num < 0:
  32.       isNegative = True
  33.       num = -num
  34.    arr = []
  35.    q, r = num, 0
  36.    while q >= radix:
  37.       q, r = divmod(q, radix)
  38.       arr.append(BASE36[r])
  39.    arr.append(BASE36[q])
  40.    if isNegative:
  41.       arr.append("-")
  42.    arr.reverse()
  43.    return ''.join(arr)
  44. def convertRadix(s, srcRdx, destRdx):
  45.     ret = ""
  46.     try:
  47.         val = int(s, srcRdx)
  48.         ret = itoa(val, destRdx)
  49.         return ret.upper()
  50.     except ValueError:
  51.         println("    Error: Cannot convert radix " + str(srcRdx))
  52.         ret = "????"
  53.     finally:
  54.         return ret.upper()
  55. def doConvert(srcRadix, destRadix):
  56.     line = ""
  57.     cmd = ""
  58.     srcStr = ""
  59.     destStr = ""
  60.     println("")
  61.     printSubMenu(srcRadix, destRadix)
  62.     try:
  63.         while True:
  64.             printSubPrompt()
  65.             cmd = raw_input()
  66.             while cmd == None:
  67.                 cmd = raw_input()
  68.             if "main()" == cmd:
  69.                 return
  70.             elif "exit()" == cmd or "quit()" == cmd:
  71.                 sys.exit(0)
  72.             try:
  73.                 int(cmd, srcRadix)
  74.                 srcStr = cmd
  75.                 destStr = convertRadix(srcStr, srcRadix, destRadix)
  76.                 println("        ( " + srcStr + " )_" + str(srcRadix) +  "   --->   ( " + destStr + " )_" + str(destRadix))
  77.                 println("")
  78.             except ValueError:
  79.                  pass
  80.     except RuntimeError:
  81.         print sys.exc_value
  82. def doStart():
  83.     line = ""
  84.     cmd = ""
  85.     srcRadix = 10
  86.     destRadix = 10
  87.     srcStr = ""
  88.     destStr = ""
  89.     onlyOnce = True
  90.     try:
  91.         while True:
  92.             println()
  93.             if onlyOnce:
  94.                 println("  The supported maximum radix is 36.")
  95.                 onlyOnce = False
  96.             printMainMenu()
  97.             printMainPrompt()
  98.             cmd = raw_input()
  99.             while cmd == None:
  100.                 cmd = raw_input()
  101.             if "qQxX".find(cmd) >= 0 and len(cmd) == 1:
  102.                 sys.exit(0)
  103.             elif "aA".find(cmd) >= 0 and len(cmd) == 1:
  104.                 printAbout()
  105.             elif "sS".find(cmd) >= 0 and len(cmd) == 1:
  106.                 line = raw_input("  Input the source and target radices (say, 16 2): ")
  107.                 st = line.split(" ")
  108.                 while len(st) < 2:
  109.                     line = raw_input("  Input the source and target radices (say, 16 2): ")
  110.                     st = line.split(" ")
  111.                 srcRadix = int(st[0])
  112.                 destRadix = int(st[1])
  113.                 doConvert(srcRadix, destRadix)
  114.     except RuntimeError:
  115.         print sys.exc_value
  116. # Begin here
  117. if len(sys.argv) > 1 and "-h" == sys.argv[1]:
  118.     printUsage()
  119.     sys.exit(1)
  120. doStart()



실행> python convertRadix.py

  The supported maximum radix is 36.
  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> s
  Input the source and target radices (say, 16 2): 10 8

    Convert Radix_10 to Radix_8
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> 200
        ( 200 )_10   --->   ( 310 )_8

    Input Value>> main()

  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> S
  Input the source and target radices (say, 16 2): 8 10

    Convert Radix_8 to Radix_10
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> 2666
        ( 2666 )_8   --->   ( 1462 )_10

    Input Value>> main()

  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> x




IronPython의 경우에는 구문

    print 스트링,

이 Python과 달리 끝에 빈칸을 곧 바로 추가하지 않고, 빈칸 출력을 유보하고 있다가 다음 print 문을 만날 때 이 빈칸을 먼저 출력한 후 주어진 스트링을 출력한다. raw_input()과 함께 쓰일 때는 이 빈칸 하나 때문에 신경이 쓰이기도 한다. 그래서 프롬프트를 출력하는 함수를

def printMainPrompt(): 
     print("  Prompt> "),

def printSubPrompt(): 
     print("    Input Value>> "),

로 수정해야 한다.




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