[Python] 코딩 도장 - Cardinal to Ordinal

Updated:

코딩 도장 사이트의 문제를 직접 풀어본 내용을 정리하여 올립니다.

코딩 도장에서 여러 문제를 확인할 수 있습니다.

난이도 순으로 차근차근 풀어보려 합니다.


[문제: Cardinal to Ordinal] - Lv.1

기수(Cardinal)를 입력하면 영어 서수(Ordinal)로 출력하는 함수를 작성합니다.

1, 21, 31, 41, ... → 1st, 21st, 31st, 41st, ...
2, 22, 32, 42, ... → 2nd, 22nd, 32nd, 42nd, ...
3, 23, 33, 43, ... → 3rd, 23rd, 33rd, 43rd, ...
11, 12, 13, 111, 112, 113, 211, 212, 213, ...  → 11th, 12th, 13th, 111th, 112th, 113th, 211th, 212th, 213th, ...
4, 5, 6, 11, 12, 13, 101, 111, 112, ... → 4th, 5th, 6th, 11th, 12th, 13th, 101th, 111th, 112th, ...

출처: https://codingdojang.com/scode/686?answer_mode=hide


[풀이]

def c_to_o():
    n = input("양의 정수를 입력하세요: ")
    if n[-1] == "1":
        return n + "st"
    elif n[-1] == "2":
        return n + "nd"
    elif n[-1] == "3":
        return n + "rd"
    else:
        return n + "th"
    
c_to_o()    
양의 정수를 입력하세요: 34





'34th'

문제에서 11은 11th 등으로 표기 되어있어 통일성이 안보이는데 우선 끝자리에 따라 구분하는 것으로 간주하였다.

input()으로 문자열을 받아 마지막 숫자를 이용해서 if문으로 풀었다.


[추천 풀이]

def CtO(s):
    Lst = s.split(', ') #문자열을 리스트로 변환
    result = []
    for i in Lst:
        if i == '1':
            Ordinal = str(i) + 'st'
            result.append(Ordinal)
        elif i == '2':
            Ordinal = str(i) + 'nd'
            result.append(Ordinal)
        elif i == '3':
            Ordinal = str(i) + 'rd'
            result.append(Ordinal)
        else:
            Ordinal = str(i) + 'th'
            result.append(Ordinal)
    print(result)


CtO('1, 2, 4, 5, 6, 11, 12, 13, 101')
['1st', '2nd', '4th', '5th', '6th', '11th', '12th', '13th', '101th']

딱히 추천 수가 많은 풀이가 없는데 이분은 그냥 1, 2, 3 외에 숫자는 th를 붙혔다.

개인적으론 이게 맞는 걸로 알고 있는데 문제가 조금 헷갈리는 부분이 있는 것 같다.

Leave a comment