-
-
Save kvid/5c4c0f65111b4c4569b2be875541e7c1 to your computer and use it in GitHub Desktop.
Check if items in list alternatingly match keys in two dicts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# fake YAML input data (only keys matter) | |
connectors = {'A': [1,2,3], 'B': [1,2,4], 'C': [3,6,7]} | |
cables = {'X': [4,4,4], 'Y': [4,5,6], 'Z': [9,9,9]} | |
# list to check, should alternatingly contain connector and cable keys, may start with either | |
listy = ['Z','A','X','B','Y','C'] | |
conkeys = list(connectors.keys()) | |
cblkeys = list(cables.keys()) | |
print('conkeys', conkeys) | |
print('cblkeys', cblkeys) | |
found_in_con = [item in conkeys for item in listy] # should contain alternating True and False | |
found_in_cbl = [item in cblkeys for item in listy] # should contain alternating False and True (reversed) | |
print('found_in_con', found_in_con) | |
print('found_in_cbl', found_in_cbl) | |
alternating = ([True, False] * ((len(listy)+1) // 2))[0:len(listy)] # generate alternating True and False list, with length = len(listy) | |
check1 = [item == check for (item, check) in zip(found_in_con, alternating)] # should contain all True if list starts with connector, all False if list starts with cable, both True and False if it does not alternate properly | |
check2 = [item != check for (item, check) in zip(found_in_con, alternating)] # same as above, but with inverted logic | |
print('check1', check1) | |
print('check2', check2) | |
starts_with_connector = all(check1) and not any(check2) | |
starts_with_cable = all(check2) and not any(check1) | |
OK = starts_with_connector or starts_with_cable | |
print('OK?', OK) | |
sections = ['connectors', 'cables', 'ferrules', 'connections'] | |
yaml_data = {'connectors': connectors, 'cables': cables} | |
start = 0 if listy[0] in yaml_data['connectors'] else 1 | |
for i, item in enumerate(listy): | |
if item not in yaml_data[sections[(start + i) % 2]]: | |
print(f"'{item}' is not in {sections[(start + i) % 2]}") | |
raise Exception('Unexpected item') | |
print(f"{len(listy)} alternating connectors and cables starting with a {sections[start][:-1]}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment