Jacob S. wrote:
Okay, not a very descriptive subject, but here goes...

This is the code

###########################################
from decimal import Decimal as D

Oh come on!

"""Everything is first converted to meters, and then converted to the unit
you want to extend usage.

dic[unit] = (unittometers,meterstounit)
"""

dic = {## Metric ##
      'm':(lambda x:x,lambda x:x),
      'km':(lambda x:1000*x,lambda x:x/1000),
      'cm':(lambda x:x/100,lambda x:100*x),
      'mm':(lambda x:x/1000,lambda x:1000*x),

      ## English ##
      'in':(lambda x:127*x/5000,lambda x:5000/(127*x)),
      'ft':(lambda x:381*x/1250,lambda x:1250/(381*x)),
      'mi':(lambda x:201168*x/125,lambda x:125/(201168*x)),
      'yd':(lambda x:1143*x/1250,lambda x:1250/(1143*x))
      }

def convert(num,unit1,unit2):
   num = D(str(num))
   tometer = dic[unit1][0](num)
   frommeter = dic[unit2][1](tometer)
   return frommeter
####################################################

Fortunately my docstrings are getting slightly better, and you can at least tell that
the function "convert" first changes the value to meters then to the second unit.

The function has no docstring. You could place this description in the docstring with a description of the parameters and their spected type.


But, I digress--to the problem...
If I call convert(3,'ft','yd'), I should get Decimal("1")
instead, I get Decimal("1.195990046301080256481500617")

Let's see. First you convert to meters with 381*x/1250 so we get... Decimal("0.9144")! OK, then you convert to "yd" using 1250/(1143*x) so we get... Decimal("1.195990046301080256481500617"). Mmmmm... OK let's Google:
3 feet = 0.9144 meters. All right!
1 yard = 0.9144 meters. Aha! It should be x/0.9144 or 1250*x/1143 instead!


Javier

PS: Sorry if this was shown further ahead but I'm too lazy to read any more.
PPS: This may be a good oportunity to start using some sort of unit test.

_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to