Skip to content

Instantly share code, notes, and snippets.

@jakeyr
Last active October 22, 2017 22:43
Show Gist options
  • Save jakeyr/34ef82dcecfdea24240daecaa97ed16f to your computer and use it in GitHub Desktop.
Save jakeyr/34ef82dcecfdea24240daecaa97ed16f to your computer and use it in GitHub Desktop.
def window(seq, n=2):
"Returns a sliding window (of width n) over data from the iterable"
" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... "
it = iter(seq)
result = tuple(islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result
def lock_is_open(combo, tumbler):
"Check if the tumbler contains the combination based on"
"a simple combination lock algorithm"
# grab the last number
final = tumbler[-1]
# cut the list down to only the numbers that are "edges",
# i.e. numbers where the lock changed direction
#
# on a traditional lock, you enter the combination and then
# attempt to open the lock to see if the final digit is correct.
# since there is no explicit “open” command in this case, tack
# on the final number (which represents the current setting of
# the Nest) before checking to see if we have a match.
check = [x[1] for x in window(tumbler,3) if max(x) == x[1] or min(x) == x[1]] + [final]
# convert the list to check into windows of len(combo) size
# this allows us to use a simple "in" operator to check if the combo
# is inside the list
check = [x for x in window(check,len(combo))]
# is the combo present in the tumbler?
return (tuple(combo) in check)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment