1/3=0 eliminator

TrustyTony 0 Tallied Votes 403 Views Share

This function I did to improve calculator program by eliminating problems with Pythons problem of dividing integer with integer and giving integer division result.

def endswithint(s):
    return not s.rstrip('0123456789').endswith('.')

def addpoint(s):
    """ returns '.' if s ends with integer, nothing if it endswith float """
    if endswithint(s): return '.'
    return ""
    

a="2+1"
b="3"
print eval(a+'/'+b) # integer division
print eval('1.0*'+a+'/'+b)  ##also does not make it

a+=addpoint(a)
print eval(a+'/'+b)
jcao219 18 Posting Pro in Training

In Python 3, 1/3 = 0.3333333333333333

snippsat 661 Master Poster

For python 2.x
eval() has a lot of power and can be safety issue in wrong hands.
a = "__import__('os').remove('important_file')"
print eval(a)

IDLE 2.6.4 
>>> from __future__ import division
>>> 1 / 3
0.33333333333333331
>>>
TrustyTony 888 ex-Moderator Team Colleague Featured Poster

I do know safety issue. That was very useful hint for my own use. Not everybody using the program has Python 2.6. Though generally for own desktop applications I think most people have possibility to keep Python updated.

I have read about Python 3 improvement. This issue just came up in GUI calculator thread, where I prepared a calculator in Tkinter for comparision. I tried this 1.0* trick first, as I was lazy to do this job of scanning the last number. Ended up to be really simple. It could be put of course one liner inline to code. But this implementation looked more self documenting.

For that calculator, the safety issue is however allready in evaluation of calculations.

One simple way at least to impove situation would be to define own eval (original with __ disallowed):

def ev(s):
    if '__' in s: return 'Safety Error'
    ## try to fix bracket unbalance 'sin(pi' for example
    brackc = s.count('(') - s.count(')')
    try:    return eval(s + ')' * brackc)
    except: return 'Error'

def endswithint(s):
    return not s.rstrip('0123456789').endswith('.')

def addpoint(s):
    """ returns '.' if s ends with integer, nothing if it endswith float """
    if endswithint(s): return '.'
    return ""

a="2+1"
b="3"
print ev(a+'/'+b) # integer division
print '1.0*2+1/3)', ev('1.0*'+a+'/'+b)  ##also does not make it

a+=addpoint(a)
print 'My solution',ev(a+'/'+b)

a="2+(1"
print "2+(1./3)", ev(a)

a = "__import__('os').remove('c:\boot.ini')"
print 'Destroy file',ev(a)
"""Output:
2
1.0*2+1/3) 2.0
My solution 2.33333333333
2+(1./3) 3
Destroy file Safety Error
"""
snippsat 661 Master Poster

This issue just came up in GUI calculator thread, where I prepared a calculator in Tkinter for comparision

Just make it a float,i have done that many time with wxpython for calculator stuff.
When push buttun i getvalue from this.

elif self.c == 'Divide':
    p = float(self.s1) / float(self.s2)
TrustyTony 888 ex-Moderator Team Colleague Featured Poster

The calculator is formula style, where you can edit the formula, with allowance of immediately evaluating before putting results to memory
see: http://www.daniweb.com/forums/post1203603.html#post1203603
plus correction post. It does have few bugs which I have corrected myself (like root change from **1/ to **1./) but I do not want to give out too finalised version for students. It suffice as prove of principle. I do have produced more unconventional calculator myself with Visual Basic, that had only number in input fields (two like you for x and y for operation x <oper> y) and basic calculations only. Special feature it had which I did not implement in this demonstration challenge (in less than 100 lines, complete calculator), where rounding of monetary values to nearest 5 cents as is rule here in Finland. Also I was converting letter O entered to 0 and , to ..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.