division

Sean Ross frobozz_electric at hotmail.com
Mon Jun 23 20:31:24 EDT 2003


>
> That works great for simple 2 number ones
>
> txt = pattern.sub(replaceint, "4/3")
> eval(txt)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<string>", line 0, in ?
>   File "<stdin>", line 6, in __div__
> __main__.ExactDivisionError: exact division only
>
>
> bit if the user types something more complex like
> >>> txt = pattern.sub(replaceint, "((4 * 5) -2) / 5  ")
> >>> eval(txt)
> 3
>
> it doesnt raise an exception even though im dividing
> 18 / 5 which doesnt go evenly .
>

Adding the following method to the myint class solves this issue:

     def __rdiv__(self, other):
            return self.__div__(other)


import re

class ExactDivisionError(Exception):
     pass

class myint(int):
     def __div__(self, other):
         "does exact division only"
         quotient, remainder = divmod(self, other)
         if remainder:
             raise ExactDivisionError, "exact division only"
         return quotient

     def __rdiv__(self, other):
        return self.__div__(other)


def replaceint(match):
     "substitues 'myint(integer)' for each matched integer"
     return 'myint(%s)'% match.string[match.start():match.end()]



 # some testing...
pattern = re.compile(r'\d+')        # matches integers
txt = '((4 * 5) -2) / 5'
txt = pattern.sub(replaceint, txt)
print txt        # 'myint(2) + myint(22)/myint(5)'

try:
     result = eval(txt)        # this will raise an exception for 'txt'
     print result
except ExactDivisionError:
     print "ExactDivisionError"


#OUTPUT
# ((myint(4) * myint(5)) -myint(2)) / myint(5)
# ExactDivisionError









More information about the Python-list mailing list