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
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)
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")
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
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)
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")