def is_list_sorted_and_valid_gap(lst):
if len(lst) < 2:
return True
increasing = all(1 <= lst[i + 1] - lst[i] <= 3 for i in range(len(lst) - 1))
decreasing = all(1 <= lst[i] - lst[i + 1] <= 3 for i in range(len(lst) - 1))
return increasing or decreasing
lst1 = [1, 2, 3, 5, 8, 11, 14, 15]
lst2 = [15, 14, 11, 8, 5, 3, 2, 1]
lst3 = [1, 2, 3, 5, 800, 11, 14, 15]
print(is_list_sorted_and_valid_gap(lst1))
print(is_list_sorted_and_valid_gap(lst2))
print(is_list_sorted_and_valid_gap(lst3))
'''
run:
True
True
False
'''