파이썬 코드 작성

조회수 1888회

16진수 글자 하나를 입력하면 16진수인지 아닌지를 구분하는 코드를 작성하시오.

1) if~else문 사용 2) and와 or을 활용

실행결과:

ex) 16진수 한글자 입력: 8

10진수 ====> 8

16진수 한글자 입력: F

10진수 ====> 15

코드를 어떻게 작성해야 할까요...

  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

  • 저번에 비슷한 질문을 올리셨는데, 이번에는 가급적 표준 라이브러리를 이용하지 않고 답변드리겠습니다.

    우선 16진수 판별은 이렇게 할 수 있습니다.

    def is_hex(c):
        is_numeric = ord('0') <= ord(c) <= ord('9')
        is_lowercase = ord('a') <= ord(c) <= ord('f')
        is_uppercase = ord('A') <= ord(c) <= ord('F')
    
        return is_numeric or is_lowercase or is_uppercase
    

    그다음, 10진수로 바꾸는 건 이렇게 할 수 있어요.

    def hex_to_dec(c):
        is_numeric = ord('0') <= ord(c) <= ord('9')
        is_lowercase = ord('a') <= ord(c) <= ord('f')
        is_uppercase = ord('A') <= ord(c) <= ord('F')
    
        if is_numeric:
            return ord(c) - ord('0')
        elif is_lowercase or is_uppercase:
            return ord(c.lower()) - ord('a') + 10
    

    모두 합치려면 이렇게 하면 되죠.

    def is_hex(c):
        is_numeric = ord('0') <= ord(c) <= ord('9')
        is_lowercase = ord('a') <= ord(c) <= ord('f')
        is_uppercase = ord('A') <= ord(c) <= ord('F')
    
        return is_numeric or is_lowercase or is_uppercase
    
    def hex_to_dec(c):
        is_numeric = ord('0') <= ord(c) <= ord('9')
        is_lowercase = ord('a') <= ord(c) <= ord('f')
        is_uppercase = ord('A') <= ord(c) <= ord('F')
    
        if is_numeric:
            return ord(c) - ord('0')
        elif is_lowercase or is_uppercase:
            return ord(c.lower()) - ord('a') + 10
    
    string = input('숫자를 입력하세요')
    if is_hex(string):
        print('16진수입니다. 10진수로 {0} 입니다.'.format(hex_to_dec(string)))
    else:
        print('16진수가 아닙니다.')
    
    • (•́ ✖ •̀)
      알 수 없는 사용자
    • 감사합니다!! 그런데 ord를 사용하지 않고 작성할 수 있는 방법은 없나요? 알 수 없는 사용자 2018.4.14 20:52
    • 글쎄요... 이게 최소한으로 표준 라이브러리를 쓰는 방법같은데요. 알 수 없는 사용자 2018.4.14 23:33

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)