Skip to content

Commit 5da01d0

Browse files
committed
-
1 parent ac20a2c commit 5da01d0

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

source_py2/python_toolbox/logic_tools.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33

44
'''This module defines logic-related tools.'''
55

6+
import collections
7+
68
from python_toolbox import cute_iter_tools
79
from python_toolbox import sequence_tools
810

@@ -30,6 +32,26 @@ def all_equal(iterable, exhaustive=False):
3032
return all(a==b for (a, b) in pairs)
3133

3234

35+
def get_equivalence_classes(iterable, key):
36+
'''
37+
Divide items in `iterable` to equivalence classes, using the key function.
38+
39+
i.e. each item will be put in a set with all other items that had the same
40+
result when put through the `key` function.
41+
42+
Returns a `dict` with keys being the results of the function, and the
43+
values being the sets of items with those values.
44+
'''
45+
key_function = \
46+
(lambda item: getattr(item, key)) if isinstance(key, str) else key
47+
equivalence_class_to_members = collections.defaultdict(set)
48+
for item in iterable:
49+
equivalence_class = key_function(item)
50+
equivalence_class_to_members[equivalence_class].add(item)
51+
52+
return equivalence_class_to_members
53+
54+
3355
def logic_max(iterable, relation=lambda a, b: (a >= b)):
3456
'''
3557
Get a list of maximums from the iterable.
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Copyright 2009-2013 Ram Rachum.
2+
# This program is distributed under the MIT license.
3+
4+
import itertools
5+
6+
from python_toolbox.logic_tools import get_equivalence_classes
7+
8+
9+
def test():
10+
assert get_equivalence_classes([1, 2, 3, 1j, 2j, 3j, 1+1j, 2+2j, 3+3j],
11+
abs) == {
12+
1: {1, 1j},
13+
2: {2, 2j},
14+
3: {3, 3j},
15+
2**0.5: {1 + 1j},
16+
8**0.5: {2 + 2j},
17+
18**0.5: {3 + 3j},
18+
}

0 commit comments

Comments
 (0)