division

kpop snag at jool.po
Mon Jun 23 16:40:47 CEST 2003

```"Sean Ross" <sross at connectmail.carleton.ca> wrote in message
news:okuJa.1035\$Fe3.161376 at news20.bellglobal.com...
> > > > 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"
>
>
> Sean
>
>

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 .

```