I have a function in which I would like to detect the first occurrence of any letter (given a group of letters) within a string and return the index of the letter(see below).
Time is critical so I am thinking of using a try/except method (see LetterDetect below).
Knowing that the try statement will fail most of the time, is this a bad practice? Secondly Would this be more efficient (time-wise) than checking every dictionary entry for the occurrence of each letter (as in LetterDetect2)?
Take the following function which looks:
def LetterDetect(s, letters):
Dct = {}
for l in letters:
Dct[ord(l)] = 0
for i in range(0, length(s)):
try:
Dct[ord(s[i])] +=1
return i
except:
pass
Versus:
def LetterDetect2(s, letters):
Dct = {}
for l in letters:
Dct[ord(l)] = 0
for i in range(0, length(s)):
if ord(s[i]) in Dct:
return i
LetterDetect("test", "abcdt")
LetterDetect2("test", "abcdt")
I appreciate any help, I am new to coding and Python. Thanks!