Update groups of equivalent elements. Given groups1 = [set1, set2, set3, ..] where all elems within each set_i is defined to be "equivalent" to each other. (but not across the sets) Incoming groups2 = [set1, set2, ...] similar to set1 - it is the additional equivalent information on elem
(
groups1: list[Any], groups2: list[Any]
)
| 179 | |
| 180 | |
| 181 | def update_groups( |
| 182 | groups1: list[Any], groups2: list[Any] |
| 183 | ) -> tuple[list[Any], list[tuple[Any, Any]], list[list[Any]]]: |
| 184 | """Update groups of equivalent elements. |
| 185 | |
| 186 | Given groups1 = [set1, set2, set3, ..] |
| 187 | where all elems within each set_i is defined to be "equivalent" to each other. |
| 188 | (but not across the sets) |
| 189 | |
| 190 | Incoming groups2 = [set1, set2, ...] similar to set1 - it is the |
| 191 | additional equivalent information on elements in groups1. |
| 192 | |
| 193 | Return the new updated groups1 and the set of links |
| 194 | that make it that way. |
| 195 | |
| 196 | Example: |
| 197 | groups1 = [{1, 2}, {3, 4, 5}, {6, 7}] |
| 198 | groups2 = [{2, 3, 8}, {9, 10, 11}] |
| 199 | |
| 200 | => new groups1 and links: |
| 201 | groups1 = [{1, 2, 3, 4, 5, 8}, {6, 7}, {9, 10, 11}] |
| 202 | links = (2, 3), (3, 8), (9, 10), (10, 11) |
| 203 | |
| 204 | Explain: since groups2 says 2 and 3 are equivalent (with {2, 3, 8}), |
| 205 | then {1, 2} and {3, 4, 5} in groups1 will be merged, |
| 206 | because 2 and 3 each belong to those 2 groups. |
| 207 | Additionally 8 also belong to this same group. |
| 208 | {3, 4, 5} is left alone, while {9, 10, 11} is a completely new set. |
| 209 | |
| 210 | The links to make this all happens is: |
| 211 | (2, 3): to merge {1, 2} and {3, 4, 5} |
| 212 | (3, 8): to link 8 into the merged({1, 2, 3, 4, 5}) |
| 213 | (9, 10) and (10, 11): to make the new group {9, 10, 11} |
| 214 | |
| 215 | Args: |
| 216 | groups1: a list of sets. |
| 217 | groups2: a list of sets. |
| 218 | |
| 219 | Returns: |
| 220 | groups1, links, history: result of the update. |
| 221 | """ |
| 222 | history = [] |
| 223 | links = [] |
| 224 | for g2 in groups2: |
| 225 | joins = [None] * len(groups1) # mark which one in groups1 is merged |
| 226 | merged_g1 = set() # merge them into this. |
| 227 | old = None # any elem in g2 that belong to any set in groups1 (old) |
| 228 | new = [] # all elem in g2 that is new |
| 229 | |
| 230 | for e in g2: |
| 231 | found = False |
| 232 | for i, g1 in enumerate(groups1): |
| 233 | if e not in g1: |
| 234 | continue |
| 235 | |
| 236 | found = True |
| 237 | if joins[i]: |
| 238 | continue |
no test coverage detected