Check to see if a string has the same amount of 'x's and 'o's. The method must return a boolean and be case insensitive. The string can contain any char.
Examples input/output:
XO("xooxx") => false
XO("ooxXm") => true
XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true
XO("zzoo") => false
So I tried to make new lists, and then append for each 'x' and each 'o' but its not quite working. Here is my code so far:
def xo(s):
ex = []
oh = []
for letter in s.split():
if letter.islower() == 'x':
ex = ex.append(letter)
elif letter.islower() == 'o':
oh = oh.append(letter)
if len(ex) == len(oh):
return True
else:
return False
It only returns True on the first ones but not on the last third. It seems to me that the code is not appending properly.
CodePudding user response:
There are (at least) three problems in your code:
s.split()
splitss
on every space and returns a list (so assuming you have no spaces, this gives you a list with a single item). Instead, just usefor letter in s:
which iterates over each letter.letter.islower()
checks if the letter is lowercased, returningTrue
orFalse
. What you want isletter.lower()
which returns the lowercased version of a character.- Also (thanks Mark) append doesn't return a value, so when you run
oh = oh.append(letter)
you are assigning a value ofNone
to theoh
variable. You should instead just useoh.append(letter)
(no assignment).
CodePudding user response:
Just use collections.Counter
.
>>> from collections import Counter
>>> c = Counter('xooxXo'.lower())
>>> c['x'] == c['o']
True
or
>>> c = Counter('xooxx'.lower())
>>> c['x'] == c['o']
False
Wrap it in your own function if you want to.
CodePudding user response:
David's answer covers some potential fixes to your code, but if you're looking for something more concise, I would suggest using .lower()
to lowercase the string upfront, and then use .count()
to count the number of Xs and Os rather than using a for
loop:
def xo(s):
return s.lower().count('x') == s.lower().count('o')
This outputs:
False