Go to Google Groups Home    comp.lang.python
Re: ten small Python programs

Steven Bethard <steven.beth...@gmail.com>

Steve Howell wrote:
> --- Steven Bethard <steven.beth...@gmail.com> wrote:
>> Very cool! Do you mind putting this up on the Wiki
>> somewhere so that we
>> can link to it more easily? Maybe something like:

>>      http://wiki.python.org/moin/SimplePrograms

> Done.

I think I would rewrite the current unit-testing example to use the
standard library unittest module::

     # Let's write reusable code, and unit test it.
     def add_money(amounts):
         # do arithmetic in pennies so as not to accumulate float errors
         pennies = sum([round(int(amount * 100)) for amount in amounts])
         return float(pennies / 100.0)
     import unittest
     class TestAddMoney(unittest.TestCase):
         def test_float_errors(self):
             self.failUnlessEqual(add_money([0.13, 0.02]), 0.15)
             self.failUnlessEqual(add_money([100.01, 99.99]), 200)
             self.failUnlessEqual(add_money([0, -13.00, 13.00]), 0)
     if __name__ == '__main__':
         unittest.main()

I believe I've still kept it to 13 lines.

STeVe

P.S. The "right" way to add money is using the decimal module, but I
couldn't think of a better example.