Home > Net >  look for indices for the smallest number and the smallest number adjacent to that number
look for indices for the smallest number and the smallest number adjacent to that number

Time:03-05

It needs to find the index of the smallest number and the index of the smallest neighboring number. If there are more such pairs, it chooses the number with the smallest indices.
for examlple:

lista = [0,4,3,2,0,5,4,0,3,4,2,0]

My first smallest value in that list is 0 so there are 6 possibilities for different pairs

0,4 with indices 0 and 1  
0,2 with indices 3 and 4  
0,5 with indices 4 and 5  
4,0 with indices 6 and 7  
2,0 with indices 10 and 11  

My second smallest value in this 6 possibilities is 2 so I have two options

0,2 with indices 3 and 4  
2,0 with indices 10 and 11  

Indexes 3 and 4 are less than 10 and 11 so the correct answer is [3, 4]

The program I tried to write but it doesn't work as expected vvv

def indices(lst, element):
    result = []
    offset = -1
    while True:
        try:
            offset = lst.index(element, offset 1)
        except ValueError:
            return result
        result.append(offset)

def search_min2(lista, max_value):
    for i in lista:
        if(i==0):
            if(lista[i 1]<max_value):
                max_value = lista[i 1]
        elif(i==len(lista)-1):
            if(lista[i-1]<max_value):
                max_value = lista[i-1]
        else:
            if(lista[i-1]<max_value):
                max_value = lista[i-1]
            if(lista[i 1]<max_value):
                max_value = lista[i 1]

        second_min = max_value
    return second_min



lista = [0,4,3,2,0,5,4,0,3,4,2,0]


min_value = 0

min_list = indices(lista, min_value)


# min2 = search_min2(min_list, max(lista))
# print(min2)

Thank you for help in advance

CodePudding user response:

You could find the first index in the range with the minimum sorted pair at that index:

i = min(range(len(lista) - 1),
        key=lambda i: sorted(lista[i : i 2]))
print(i, i 1)

Prints 3 4.

  • Related