Skip to content

Instantly share code, notes, and snippets.

@formatc1702
Last active July 11, 2020 08:40
Show Gist options
  • Save formatc1702/688fc6047b8744d4c3ed6cafb098d7de to your computer and use it in GitHub Desktop.
Save formatc1702/688fc6047b8744d4c3ed6cafb098d7de to your computer and use it in GitHub Desktop.
Check if items in list alternatingly match keys in two dicts
# 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 = ['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)
@kvid
Copy link

kvid commented Jul 10, 2020

One drawback with the approach to test all items together by comparing lists, is that it might not be so easy to report the first item that is unexpected. A simple naive approach is to test the first item for all alternatives, and then in a loop, test for alternating item is connector or cable/wire. Then the first unexpected value is easy to report. As a user, I would prefer a report on the first unecpected value together with a description of what was expected.

@formatc1702
Copy link
Author

Very good point!

@kvid
Copy link

kvid commented Jul 11, 2020

@formatc1702
Copy link
Author

I like it! I'll build on that. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment