Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to check if a list is all increasing or decreasing and the gap between numbers is 1, 2 or 3 in Python

1 Answer

0 votes
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
  
'''

 



answered Jan 12, 2025 by avibootz
edited Jan 12, 2025 by avibootz
...