[Tutor] correcting an Active State Recipe for conversion to ordinal

Kent Johnson kent37 at tds.net
Thu Feb 4 21:40:36 CET 2010


On Thu, Feb 4, 2010 at 1:21 PM, Serdar Tumgoren <zstumgoren at gmail.com> wrote:
>> Perhaps the code on activestate is not a correct copy of what you are
>> running? The conditional at line 23 extends all the way to line 35 -
>> the end of the function - so if value % 100/10 == 1 no more code is
>> executed and None is returned.
>>
>
> Here is the code that I'm running locally (hopefully the formatting
> doesn't get screwed up):
>
> def ordinal(value):
>    """
>    Converts an integer to it's ordinal as a string.
>    For example 1 to "1st", 2 to "2nd", 3 to "3rd", etc.
>    """
>    try:
>        value = int(value)
>    except ValueError:
>        return value
>
>    if value % 100/10 <> 1:
>        if value % 10 == 1:
>            ord = u"%d%s" % (value, "st")
>            return ord
>        elif value % 10 == 2:
>            ord = u"%d%s" % (value, "nd")
>            return ord
>        elif value % 10 == 3:
>            ord = u"%d%s" % (value, "rd")
>            return ord
>        else:
>            ord = u"%d%s" % (value, "th")
>            return ord
>    else:
>        ord = u"%d%s" % (value, "th")
>        return  ord

There is no need to duplicate the last 'else' clause. All the previous
cases return so just make it fall through to the general case:

   if value % 100/10 <> 1:
       if value % 10 == 1:
           ord = u"%d%s" % (value, "st")
           return ord
       elif value % 10 == 2:
           ord = u"%d%s" % (value, "nd")
           return ord
       elif value % 10 == 3:
           ord = u"%d%s" % (value, "rd")
           return ord

       ord = u"%d%s" % (value, "th")
       return  ord

If you want value % 100/10 to give the same result in Python 2.6 and
Python 3 you can use value % 100//10 which will always use integer
division.

Kent


More information about the Tutor mailing list