Compare the total occurrence of two characters from a string

In this short example we are going to compare the total occurrence of two characters from a string using python program. If the total occurrence of those two characters is the same then the program will return true, otherwise return false. You also need to return true if there is no such two characters in that string.

The original question is asking us to compare the total occurrence of both x and o character but I have modified it so we can compare any two characters as we wish to. We also need to make sure we can compare the total occurrence of those characters regardless of lower or uppercase character.

def xo(s, ch1, ch2):
    x = 0
    o = 0
    for char in s:
        character = char.lower()
        if(character == ch1):
            x += 1
        elif(character == ch2):
            o += 1
    if(x == o or x == 0 or o == 0):
        return True
    else:
        return False

print(xo('hxelloOx', 'x', 'o')) # the parameters are, the string, the first and the second character

Enter the above code into Visual Studio Code IDE or any of your favorite IDE and run it!

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of