lets say I have a string y =’rtgxpsa’
if the character ‘x’ is in the string it has to be followed by the character ‘p’ or ‘z’ for the function to return True, if it is followed by any other character it returns False.
I cant find any example for something specifically like this
but I did try this
def find(word)
for i in word:
if i == 'x' and i+1 == 'p' or i+1 == 'z':
return True
else:
return False
print(def('rtgxpsa'))
Any help would be appreciated ! don’t hesitate asking if you need more details !
>Solution :
Your function should look like this
def find(word):
for i, current_letter in enumerate(word):
if current_letter == 'x' and (word[i+1] == 'p' or word[i+1]== 'z'):
return True
return False
print(find('rtgxpsa'))
enumerate(word) returns a generator that has a tuple of the index and the current value
Despite that, your algorithm can be approached differently to be more concise
def find(word):
return "xp" in word or "xz" in word