division

Sean Ross sross at connectmail.carleton.ca
Sun Jun 22 23:19:56 EDT 2003


> > > The problem is division, I would like it that only exact division was
> > > aloud, I mean no remainders.

> > > i would like if that was illegal because 5 doesnt go into 22 , 4 times
> > > exactly, and have the eval function raise an execption which i could
> > > handle.


I'm not going to ask why you want this behaviour, I'm just going to offer a
quick, dirty, and possibly buggy solution.

This code relies on the following assumptions:
[1]  You want to ensure that *only* exact division can occur
[2]  The only numbers your users can *ever* enter are integers,  i.e.  '2.0
+ 3.14' will raise an exception.

So, for this to work, you'll need to somehow ensure [2]. A more reliable
solution would be to make your own simple interpreter. I would recommend
checking out SPARK. There are examples available with the software that you
could extend to fit your problem domain. Anyway, here's some code. I won't
guarantee its robustness, I'll just say it appears to work.


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 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 = '2 + 22/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"


Hope that's helpful,
Sean






More information about the Python-list mailing list