Implement C's Switch in Python 3

John Sanders jldsand at skybeam.com
Tue Feb 5 19:25:54 EST 2019


On Saturday, February 2, 2019 at 6:47:49 PM UTC-6, Sayth Renshaw wrote:
> Hi
> 
> I am trying to convert a switch statement from C into Python. (why? practising).
> 
> This is the C code. 
> 
> printf("Dated this %d", day);
>   switch (day) {
>     case 1: case 21: case 31:
>         printf("st"); break;
>     case 2: case 22:
>         printf("nd"); break;
>     case 3: case 23:
>         printf("rd"); break;
>     default: printf("th"); break;
>     
>   }
>   printf(" day of ");
> 
> #Premise if the use enter an int as the date 21 for example it would print 21st. It appends the correct suffix onto a date.
> 
> Reading and trying to implement a function that uses a dictionary. Not sure how to supply list into it to keep it brief and with default case of 'th'.
> 
> This is my current code.
> 
> def f(x):
>     return {
>         [1, 21, 31]: "st",
>         [2, 22]: "nd",
>         [3, 23]: "rd",
>     }.get(x, "th")
> 
> 
> print(f(21))
> 
> I have an unhashable type list. Whats the best way to go?
> 
> Cheers
> 
> Sayth

My best, readable attempt good for 1 - 99:

def sufx( day ):
    if (day % 10) in [0,4,5,6,7,8,9] or (day / 10) == 1:  
        return 'th'
    return {1: 'st', 2: 'nd', 3: 'rd'}[day % 10]



More information about the Python-list mailing list