r/PythonLearning • • May 06 '26

Can I do this more efficiently?

Post image

I am working through Al Sweigart’s book ‘Python Programming Exercises, Gently Explained’ and just completed exercise 6:
“In English, ordinal numerals have suffixes such as the "th" in "30th" or "nd" in "2nd". Write an ordinalSuffix() function with an integer parameter named number and returns a string of the number with its ordinal suffix. For example, ordinalSuffix(42) should return the string
'42nd'.”
Can I improve my solution? I feel there must be a more pythonic way of doing this, I’m not very happy with converting the integer to a string and then to a list.

153 Upvotes

47 comments sorted by

View all comments

1

u/Impossible_Video_116 May 06 '26 edited May 06 '26

The following is I believe most optimised and pythonic way to do it with edge case and error handling.

def ordinalSuffix(num: int) -> str:
    if num<1:
        raise ValueError("Only positive integers are allowed")
    elif num//10==1:
       return str(num) + "th"
    match(num%10):
        case 1:
            return str(num) + "st"
        case 2:
            return str(num) + "nd"
        case 3:
            return str(num) + "rd"
        case _:
            return str(num) + "th"
    return "" #this statement will never get executed, needed for explicit str return

2

u/bloody-albatross May 06 '26
>>> ordinalSuffix(211)
    '211st'

1

u/Impossible_Video_116 May 06 '26

Sorry, i didn't think of that, my bad