[Coderbyte] – AB Check [Easy]
2019 Jan 14th
Have the function ABCheck(str) take the str parameter being passed and return the string true if the characters a and b are separated by exactly 3 places anywhere in the string at least once (ie. “lane borrowed” would result in true because there is exactly three characters between a and b). Otherwise return the string false.
I have tried to avoid using a for loop for this solution, and I got a half-working solution. Thus, I have chosen the alternative way of looping over the string and checking if the current character is ‘a’ followed by ‘b’ with exactly three characters between them. The solution checks the other way around too – if the current character is ‘b’ and if the character at three positions further is ‘a’.
To access a different position in the given string rather than the current one, a for loop with range is used. The range takes the length of the string as an argument minus four.
for pos in range(len(str)-4):
The reason for doing this is that I want to check if the character at three positions further is either ‘b’ or ‘a’. If the ‘minus four’ part is missing, then the solution results in an error. The for loop starts at position 0, which is the reason why four is used instead of three.
if str[pos] == 'a' and str[pos+4] == 'b': return 'true' elif str[pos] == 'b' and str[pos+4] == 'a': return 'true'
If the character at the current position is ‘a’/ ‘b’ followed by ‘b’/’a’ with exactly three characters between them, then it returns true. If these conditions are not fulfilled, it just returns false.
The full solution is pasted below:
def ABCheck(str): for pos in range(len(str)-4): if str[pos] == 'a' and str[pos+4] == 'b': return 'true' elif str[pos] == 'b' and str[pos+4] == 'a': return 'true' return 'false'