get the position of an element in a list of characters python

Question:

I have the following 2 functions to obtain the position of a letter within the alphabet list, the functions only work for the first element A or B with the following letters giving -1 or outside the index range


alfabeto=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]

pos2=int(m/2)
letra="B"

#first function 

def bus_letter(alfabeto,letra):
 for index, element in enumerate(alfabeto):
           if element==letra:
               return index
           return -1


#second function 

def pos_alf(alfabeto,pos2,letra):
    
    if alfabeto[pos2]==letra:
        return pos2
    elif alfabeto[pos2]>letra:
        return pos_alf(alfabeto,int(pos2/2),letra)
    else:
        return pos_alf(alfabeto,pos2+int(pos2/2),letra)
      

solution suggestions

Asked By: Anna Reyes

||

Answers:

Function 1:

def bus_letter(alfabeto,letra):
    for index, element in enumerate(alfabeto):
        if element==letra:
            return index
    return -1

Function 2:

def pos_alf(alfabeto,pos2,letra):
    if pos2 < 0 or pos2 >= len(alfabeto):
        return -1
    if alfabeto[pos2]==letra:
        return pos2
    elif alfabeto[pos2]>letra:
        return pos_alf(alfabeto,int(pos2/2),letra)
    else:
        return pos_alf(alfabeto,pos2+int(pos2/2),letra)
Answered By: Nova

I found a solution by handling the alphabet list as a string and looping through the string until it gets the character that matches and returns the position

alf="ABCDEFGHIJKLMNOPQRSTUVWXYZ"

def find_pos(caracter):
    posi=0
    for i in range(len(alf)):
        if caracter==alf[i]:
            posi=i+1
            return posi

        else:
            print("Not found")
            


Answered By: Anna Reyes
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.