Implement C's Switch in Python 3
MRAB
python at mrabarnett.plus.com
Tue Feb 5 19:48:43 EST 2019
On 2019-02-06 00:25, John Sanders wrote:
> 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]
>
In Python 3, 11/10 == 1.1, not 1.
More information about the Python-list
mailing list