On Sunday, 3 February 2019 14:31:14 UTC+11, Avi Gross wrote: > Yes, you caught the usual flaw in the often irregular English language. > > The 11th, 12th and 13th do all begin with 1 so there is a simple fix in the > function version by checking if day//10 is 1. > > Revised example: > > """ Use last digit to determine suffix handling teens well """ > > def nthSuffix(day): > if (day // 10 == 1): > suffix = "th" > else: > nth = day % 10 > suffix = "st" if nth == 1 else ("nd" if nth == 2 else ("rd" if nth > == 3 else "th")) > > return str(day) + suffix > > >>> [ nthSuffix(day) for day in range(1,32)] > ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th', > '11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', > '20th', '21st', '22nd', '23rd', '24th', '25th', '26th', '27th', '28th', > '29th', '30th', '31st'] > > Want a dictionary version? Use the above to make a full dictionary: > > >>> chooseFrom = { day : nthSuffix(day) for day in range(1,32)} > >>> chooseFrom > {1: '1st', 2: '2nd', 3: '3rd', 4: '4th', 5: '5th', 6: '6th', 7: '7th', 8: > '8th', 9: '9th', 10: '10th', 11: '11th', 12: '12th', 13: '13th', 14: '14th', > 15: '15th', 16: '16th', 17: '17th', 18: '18th', 19: '19th', 20: '20th', 21: > '21st', 22: '22nd', 23: '23rd', 24: '24th', 25: '25th', 26: '26th', 27: > '27th', 28: '28th', 29: '29th', 30: '30th', 31: '31st'} > >>> chooseFrom[1] > '1st' > >>> chooseFrom[11] > '11th' > >>> chooseFrom[21] > '21st' >
> Subject: Re: Implement C's Switch in Python 3 > > On 2019-02-03 02:51, Avi Gross wrote: > > I may be missing something, but the focus seems to be only on the > > rightmost digit. You can get that with > > > I had the same thought, but came across a problem. "11st", "12nd", "13rd"? > > [snip] > > > > Output: > > > >>>> for day in range(1, 32): > > print( nthSuffix(day)) > > > > 1st > > 2nd > > 3rd > > 4th > > 5th > > 6th > > 7th > > 8th > > 9th > > 10th > > 11st > > 12nd > > 13rd > > 14th > > 15th > > 16th > > 17th > > 18th > > 19th > > 20th > > 21st > > 22nd > > 23rd > > 24th > > 25th > > 26th > > 27th > > 28th > > 29th > > 30th > > 31st > > > [snip] > -- I do like this. Want a dictionary version? Use the above to make a full dictionary: >>> chooseFrom = { day : nthSuffix(day) for day in range(1,32)} >>> chooseFrom {1: '1st', 2: '2nd', 3: '3rd', 4: '4th', 5: '5th', 6: '6th', 7: '7th', 8: '8th', 9: '9th', 10: '10th', 11: '11th', 12: '12th', 13: '13th', 14: '14th', 15: '15th', 16: '16th', 17: '17th', 18: '18th', 19: '19th', 20: '20th', 21: '21st', 22: '22nd', 23: '23rd', 24: '24th', 25: '25th', 26: '26th', 27: '27th', 28: '28th', 29: '29th', 30: '30th', 31: '31st'} >>> chooseFrom[1] '1st' >>> chooseFrom[11] '11th' >>> chooseFrom[21] '21st' Not having a default case as in switch forced you to write out all possible combinations. I think the intent and readbility of switch statements is a bit nicer. Cheers Sayth -- https://mail.python.org/mailman/listinfo/python-list