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,919 questions

51,852 answers

573 users

How to find the nearest smaller element on left side of each element of a list in Python

1 Answer

0 votes
def smaller_index(arr, pos):
    i = pos - 1
    index = -1
       
    while i >= 0 and index == -1:
        if (arr[i] < arr[pos]):
            index = i
        i -= 1
        
    return index;
    
def nearest_smaller(arr):
    index = 0
    size = len(arr)
          
    for i in range(0, size):
        index = smaller_index(arr, i)
       
        if (index == -1):
            print(arr[i], ": No Smaller");
        else:
            print(arr[i], ":", arr[index]);

        
lst = [4, 6, 2, 8, 6, 1, 9, 12, 3, 20, 18, 30]
  
nearest_smaller(lst)

  
  
  
'''
run:
   
4 : No Smaller
6 : 4
2 : No Smaller
8 : 2
6 : 2
1 : No Smaller
9 : 1
12 : 9
3 : 1
20 : 3
18 : 3
30 : 18
   
'''

 



answered Dec 19, 2021 by avibootz
...