[Coderbyte] – Ex Oh [Easy]
2019 Jan 10th
The Ex Oh Coderbyte challenge checks if there is an equal number of x’s and o’s in a given string. The requirements of the problem are as follows:
Have the function ExOh(str) take the str parameter being passed and return the string true if there is an equal number of x‘s and o‘s, otherwise return the string false. Only these two letters will be entered in the string, no punctuation or numbers. For example: if str is “xooxxxxooxo” then the output should return false because there are 6 x’s and 5 o’s.
As the challenge asks us to find the number of o’s and x’s, the first step is to create two different variables: one that counts the letter x and another one that counts the letter o. Each time one of the letters is found, the appropriate variable is incremented.
def ExOh(str): countX = 0 countO = 0
To check how many x’s and o’s a given string contains, there must be a for loop that iterates over all the characters from the string. While iterating over the string, we check if the specific letter is either x or o. If it is, the appropriate variable is incremented.
def ExOh(str): countX = 0 countO = 0 for chr in str: if chr == 'x': countX += 1 if chr == 'o': countO += 1
The last step is to return the result of comparing the two variables. If they both contain the same value, the string has an equal number of x’s and o’s. The full solution is below:
def ExOh(str): countX = 0 countO = 0 for chr in str: if chr == 'x': countX += 1 if chr == 'o': countO += 1 return countX == countO
Other answers or critics for the above solution are highly appreciated.