Home > database >  Python: How to search a list from the middle outwards instead of searching from left to right like d
Python: How to search a list from the middle outwards instead of searching from left to right like d

Time:03-24

My list looks like this list = ["a","b","c","b","a","c","b"] and I want to be able to search from the middle index outwards to find the first available "a". Using this logic it should search from index 3 then search indexes 2 and 4, then search indexes 1 and 5 then finally search indexes 0 and 6. If we apply this logic to our list, we search the list at index3 for "a" and it doesn't work, so we search indexes2 and 4 for "a" and we find it at index4

I tried using list.index("a") but that just returns the first available "a" at index0 when in reality I want the "a" at index4 since it is the closest to index3. I'm sorry if the answer is obvious, I am new to python and want to be able to search lists like this for a project of mine

I think I know a solution is to be able to start the search at index3 in the right direction and to also start a simultaneous search at index 3 in the left direction but I have no clue how to search in the left direction

EDIT: is there also a way to make it work if the middle is offset?

CodePudding user response:

Try some good old math to get the middle element of the list.

mylist =  ["a","b","c","b","a","c","b"]
middle_index = (len(mylist) -1) / 2 # -1 since lists start at 0
middle_index = round(middle_index) # use round() if the list is even and middle_index variable is a float.

for index in range(middle_index): # loop over half the list
    value1 = mylist[middle_index-index] # get the variable left of the index
    value2 = mylist[middle_index index] # get the variable right of the index
    if value1 == is "a":
        print("found!")
    if value2 == is "a":
        print("found!")
    

CodePudding user response:

list.index give the index (index start from 0) for the first match item.

so this function work on list from left to right from 0th index to last index.

so if you want to search outward from the mid then you need to pass the new arry (partitioned one) to get the index from there.

for example in

arr=[0,1,2,3,4,5,4,3,2,1,0]

if you want to search value 1 from value 5 ie index 6 toward left and right then one of the way to do is

center_index = 6 # index of value 5
left_index = center_idex - arr[:6][::-1].index(1)   # reversing the arr values till index 6 and getting the index then
right_index = center_index   arr[6:].index(1)

if there is no search value then valueerror will occur.

  • Related