• API
• FAQ
• Tools
• Archive
SHARE
TWEET

# singledispatch, recursion, isclose

DeaD_EyE Oct 26th, 2019 (edited) 99 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. #!/usr/bin/python3
2. """
3. Example with singledispatch and a little bit recursion
4. """
5.
6. from functools import singledispatch
7. from itertools import zip_longest
8. from math import isclose
9. from pprint import pprint
10.
11.
12. def print_level_name(name, level):
13.     print(f'{"-" * level} {name.title()} Level: {level}')
14.
15.
16. @singledispatch
17. def compare(a, b, level=1):
18.     print_level_name('generic', level)
19.     return a == b
20.
21.
22. @compare.register(int)
23. @compare.register(float)
24. def compare_float(a, b, level=1):
25.     print_level_name('sequence', level)
26.     return isclose(a,b)
27.
28.
29. @compare.register(dict)
30. def compare_dict(a, b, level=1):
31.     print_level_name('dict', level)
32.     if a.keys() ^ b.keys():
33.         return False
34.     for akey, avalue in a.items():
35.         bvalue = b.get(akey)
36.         if not compare(avalue, bvalue, level=level+1):
37.             return False
38.     return True
39.
40.
41. @compare.register(list)
42. @compare.register(tuple)
43. def compare_sequence(a, b, level=1):
44.     print_level_name('sequence', level)
45.     for avalue, bvalue in zip_longest(a, b, fillvalue=...):
46.         if not compare(avalue, bvalue, level=level+1):
47.             return False
48.     return True
49.
50.
51. @compare.register(frozenset)
52. @compare.register(set)
53. def compare_set(a, b, level=1):
54.     print_level_name('set', level)
55.     rest = sorted(a ^ b)
56.     if len(rest) % 2 != 0:
57.         return False
58.     while rest:
59.         val1 = rest.pop()
60.         val2 = rest.pop()
61.         if not compare(val1, val2, level=level+1):
62.             return False
63.     return True
64.
65.
66. d1 = {
67.     'color': 'red', 'id': 5, 'value': 10.0, 'sd': {
68.         'value': 4.4, 'foo': [
69.             1, 2, 3, [
70.                 4, {
71.                     0.1 + 0.2,
72.                     }
73.                 ]
74.             ]
75.         }
76.      }
77.
78. d2 = {
79.     'color': 'red', 'id': 5, 'value': 10.0, 'sd': {
80.         'value': 4.4, 'foo': [
81.             1, 2, 3, [
82.                 4, {
83.                     0.3,
84.                     }
85.                 ]
86.             ]
87.         }
88.      }
89.
90. print('Input Data D1')
91. pprint(d1)
92. print()
93. print('Input Data D2')
94. pprint(d2)
95. print()
96. result = compare(d1, d2)
97. if result:
98.     print('Both objects are equal')
99. else:
100.     print('Objects are not equal')
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.
Top