git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Implement C's Switch in Python 3


On Sun, Feb 3, 2019 at 11:51 AM Sayth Renshaw <flebber.crue at gmail.com> 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?

What you really want there is for 1 to map to "st", and 21 to
separately map to "st", not for some combined key [1, 21, 31] to map
to "st". There's no easy syntax for this, and maybe a helper function
would, well, help.

def mapper(*plans):
    plans = iter(plans)
    d = {}
    while "moar plans":
        try: keys = next(plans)
        except StopIteration: return d
        value = next(plans)
        for key in keys: d[key] = value

def f(x):
    return mapper(
        [1, 21, 31], "st",
        [2, 22], "nd",
        [3, 23], "rd",
    ).get(x, "th")

Of course, you can also precompute this:

day_ordinal = mapper(
        [1, 21, 31], "st",
        [2, 22], "nd",
        [3, 23], "rd",
)
def f(x): return day_ordinal.get(x, "th")

ChrisA