getting positions for set of characters in a python string
set of character :
string="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
charPositionToFind=A,D,V,Y
expected Output
postions=[0,3,21,24]
i do it this way
def find_all(string,char):
return [i - 1 for i in range(len(string)) if string.startswith(char, i - 1)]
string="ABCDEYYFGHIAAJKVLMNOPDCQRSTAAVVVUVWXYZ"
charPositionToFind=['A','D','V','Y']
position=[]
for char in charPositionToFind:
s = find_all(string,char)
position.extend(s)
print sorted(position)
output:
[0, 3, 5, 6, 11, 12, 15, 21, 27, 28, 29, 30, 31, 33, 36]
But i want the best way to do this
string.index would be nice to use, but there are two issues with it.
1) It only finds the first occurence of the character, and
2) It raise an error if the character is not found, necessitating a check for existence before using index().
Looking at the problem simplistically, these are two easy approaches to the problem:
Method 1:
Method 2:
Runtime wise, the two methods have the same worst case of O(N x M), where N is the size of string and M is the size of charPositionToFind. However, using method 1 allows you to remove the inner loop by using a set. It also avoids having to do a sort at the end, since you are iterating through the characters of string in order. So, using list comprehension to avoid for loops: