takes an array `arr` and function `fn` and returns a dictionary with keys fn(ob) for each ob in `arr` and with values `self.arr[key]` a list of all objects in `arr` satisfying `key == fn(ob)`.
| 80 | |
| 81 | |
| 82 | class Grouper: |
| 83 | """ |
| 84 | takes an array `arr` and function `fn` and returns a dictionary |
| 85 | with keys fn(ob) for each ob in `arr` and with values `self.arr[key]` a list of all |
| 86 | objects in `arr` satisfying `key == fn(ob)`. |
| 87 | """ |
| 88 | |
| 89 | def __init__(self, arr, fn) -> None: |
| 90 | # self.orig_arr = arr |
| 91 | self.size = len(arr) |
| 92 | arr = list(enumerate(arr)) |
| 93 | |
| 94 | def group_return_dict(arr, fn): |
| 95 | res = collections.defaultdict(list) |
| 96 | |
| 97 | for ob in arr: |
| 98 | res[fn(ob)].append(ob) |
| 99 | return res |
| 100 | |
| 101 | arr = group_return_dict(arr, lambda x: fn(x[1])) |
| 102 | |
| 103 | # self.arr has format Dict[Tuple[int, <entry from orig. arr>]] |
| 104 | self.arr = arr |
| 105 | self._grouped = None |
| 106 | |
| 107 | def get_grouped(self): |
| 108 | # return the contents but not indices for our grouped dict. |
| 109 | if self._grouped: |
| 110 | return self._grouped |
| 111 | grouped = {} |
| 112 | for key in self.arr.keys(): |
| 113 | # drop the index from each element of self.arr |
| 114 | grouped[key] = [y[1] for y in self.arr[key]] |
| 115 | self._grouped = grouped |
| 116 | return grouped |
| 117 | |
| 118 | def get_original(self, grouped_dict): |
| 119 | # take in a grouped dictionary with e.g. results for each key listed |
| 120 | # in the same order as the instances in `self.arr`, and |
| 121 | # return the results in the same (single list) order as `self.orig_arr`. |
| 122 | res = [None] * self.size |
| 123 | cov = [False] * self.size |
| 124 | # orig = [None] * self.size |
| 125 | |
| 126 | assert grouped_dict.keys() == self.arr.keys() |
| 127 | |
| 128 | for key in grouped_dict.keys(): |
| 129 | for (ind, _), v in zip(self.arr[key], grouped_dict[key]): |
| 130 | res[ind] = v |
| 131 | cov[ind] = True |
| 132 | # orig[ind] = _ |
| 133 | |
| 134 | assert all(cov) |
| 135 | # assert orig == self.orig_arr |
| 136 | |
| 137 | return res |
| 138 | |
| 139 |
nothing calls this directly
no outgoing calls
no test coverage detected