1
|
|
|
"""Functions to utilize lists of Comparable objects.""" |
2
|
|
|
|
3
|
|
|
|
4
|
|
|
def find_equal(base, items): |
5
|
|
|
"""Get an iterator of items equal to the base. |
6
|
|
|
|
7
|
|
|
@param base: base item to find equality |
8
|
|
|
@param items: list of items for comparison |
9
|
|
|
@return: generator of equal items |
10
|
|
|
|
11
|
|
|
""" |
12
|
|
|
return (item for item in items if base.equality(item)) |
13
|
|
|
|
14
|
|
|
|
15
|
|
|
def match_equal(base, items): |
16
|
|
|
"""Get the first item that is equivalent to the base. |
17
|
|
|
|
18
|
|
|
@param base: base item to find equality |
19
|
|
|
@param items: list of items for comparison |
20
|
|
|
@return: first equivalent item or None |
21
|
|
|
|
22
|
|
|
""" |
23
|
|
|
for item in find_equal(base, items): |
24
|
|
|
return item |
25
|
|
|
|
26
|
|
|
return None |
27
|
|
|
|
28
|
|
|
|
29
|
|
|
def find_similar(base, items): |
30
|
|
|
"""Get an iterator of items similar to the base. |
31
|
|
|
|
32
|
|
|
@param base: base item to locate best match |
33
|
|
|
@param items: list of items for comparison |
34
|
|
|
@return: generator of similar items |
35
|
|
|
|
36
|
|
|
""" |
37
|
|
|
return (item for item in items if base.similarity(item)) |
38
|
|
|
|
39
|
|
|
|
40
|
|
|
def match_similar(base, items): |
41
|
|
|
"""Get the most similar matching item from a list of items. |
42
|
|
|
|
43
|
|
|
@param base: base item to locate best match |
44
|
|
|
@param items: list of items for comparison |
45
|
|
|
@return: most similar matching item or None |
46
|
|
|
|
47
|
|
|
""" |
48
|
|
|
finds = list(find_similar(base, items)) |
49
|
|
|
if finds: |
50
|
|
|
return max(finds, key=base.similarity) # TODO: make O(n) |
51
|
|
|
|
52
|
|
|
return None |
53
|
|
|
|
54
|
|
|
|
55
|
|
|
def duplicates(base, items): |
56
|
|
|
"""Get an iterator of items similar but not equal to the base. |
57
|
|
|
|
58
|
|
|
@param base: base item to perform comparison against |
59
|
|
|
@param items: list of items to compare to the base |
60
|
|
|
@return: generator of items sorted by similarity to the base |
61
|
|
|
|
62
|
|
|
""" |
63
|
|
|
for item in items: |
64
|
|
|
if item.similarity(base) and not item.equality(base): |
65
|
|
|
yield item |
66
|
|
|
|
67
|
|
|
|
68
|
|
|
def sort(base, items): |
69
|
|
|
"""Get a sorted list of items ranked in descending similarity. |
70
|
|
|
|
71
|
|
|
@param base: base item to perform comparison against |
72
|
|
|
@param items: list of items to compare to the base |
73
|
|
|
@return: list of items sorted by similarity to the base |
74
|
|
|
|
75
|
|
|
""" |
76
|
|
|
return sorted(items, key=base.similarity, reverse=True) |
77
|
|
|
|