Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
sliding_window solution in Clear category for Missing Number by perimeter
from collections import deque
from itertools import islice
def missing_number(items: list[int]) -> int:
#from itertools recipes
def sliding_window(iterable, n):
"Collect data into overlapping fixed-length chunks or blocks."
# sliding_window('ABCDEFG', 4) → ABCD BCDE CDEF DEFG
iterator = iter(iterable)
window = deque(islice(iterator, n - 1), maxlen=n)
for x in iterator:
window.append(x)
yield tuple(window)
def is_gap(x, y, z):
return y - x != z - y
def missing(x, y, z):
reverse_gap = y - x
forward_gap = z - y
#if only 1 number is missing from sequence
#then the bigger gap is a multiple of the
#smaller gap
if reverse_gap < forward_gap:
return y + reverse_gap
else:
return x + forward_gap
s = sorted(items)
for x, y, z in sliding_window(s, 3):
if is_gap(x, y, z):
return missing(x, y, z)
print("Example:")
print(missing_number([1, 4, 2, 5]))
# These "asserts" are used for self-checking
assert missing_number([1, 4, 2, 5]) == 3
assert missing_number([2, 6, 8]) == 4
print("The mission is done! Click 'Check Solution' to earn rewards!")
Jan. 5, 2025
Comments: