Last active
August 29, 2015 14:13
-
-
Save juanplopes/262de3050cc2c77b55f9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import unittest, numbers | |
class AlmostNumber: | |
def __init__(self, number, delta): | |
self.number = number | |
self.delta = delta | |
def __eq__(self, other): | |
return abs(self.number-other) < self.delta | |
def __repr__(self): | |
return repr(self.number) | |
def almost(obj, delta=1e-6): | |
if isinstance(obj, numbers.Number): | |
return AlmostNumber(obj, delta) | |
if isinstance(obj, dict): | |
return {almost(x, delta): almost(y, delta) for x, y in obj.items()} | |
if isinstance(obj, (list, tuple, set)): | |
return type(obj)(almost(x, delta) for x in obj) | |
return obj | |
class AlmostTest(unittest.TestCase): | |
def test_example(self): | |
self.assertEquals(almost([1, 2]), [1.0, 1.99999999999]) | |
self.assertEquals(almost({'a':1, 'b':2}), {'a':1.0, 'b':1.99999999999}) | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment