Description:
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 contains any char.
Examples input/output:
xo("ooxx") => true
xo("xooxx") => false
xo("ooxXm") => true
xo("zpzpzpp") => true // when no 'x' and 'o' is present should return true
xo("zzoo") => false
=========================================================================================================
首先,我的最笨的做法,即设置两个计数器,然后遍历字符串,对两个字母进行计数,若最后计数值相等,则返回True,若计数值不等,则返回False
。
def xo(s):
count_x = count_o = 0
for ch in s:
if ch.lower() == 'x':
count_x += 1
elif ch.lower() == 'o':
count_o += 1
if count_x == count_o:
return True
else:
return False
初学Python,练习太少,果然是不行的,就这个一个简单的小程序,竟然犯了两个错误,(1)for循环中ch最初写为chr,由于网页编辑器没有高亮,竟然不知道用到了内置函数的名字;(2)True和False习惯性地小写成了true和false
=========================================================================================================
提交后看到了别人的答案,才不得不佩服。总结了一下,有以下几种聪明的做法:
------------------------------------------------------------------------------------------------------------------------------------------
(1)利用内置函数str.count
def xo(s):
s = s.lower()
return s.count('x') == s.count('o')
同样的,还有人这么写(one-line python):
def xo(s):
return s.lower().count('x') == s.lower().count('o')
str.count方法是我没有用过的,涨知识了。
------------------------------------------------------------------------------------------------------------------------------------------
(2)利用collections.Counter
from collections import Counter
def xo(s):
d = Counter(s.lower())
return d.get('x', 0) == d.get('o', 0)
下面的是同样的做法:
def xo(s):
c = __import__('collections').Counter(s.lower())
return c['x'] == c['o']
------------------------------------------------------------------------------------------------------------------------------------------
(3)利用字符串函数replace分别去掉字符‘o’和‘x’,比较剩下内容的长度
def xo(s):
return len(s.lower().replace('x','')) == len(s.lower().replace('o',''))
------------------------------------------------------------------------------------------------------------------------------------------
(4)下面是一种比较妙的思路
def xo(s):
i=0
for c in s:
if c=='x' or c=='X':
i+=1
elif c=='o' or c=='O':
i-=1
if i==0:
return True
else:
return False
同样的,还有人这么写:
VALUES = {'x': 1, 'X': 1, 'o': -1, 'O': -1}
def xo(s):
return not sum(VALUES.get(a, 0) for a in s)
------------------------------------------------------------------------------------------------------------------------------------------
(5)lambda函数,整个函数加函数体就一行
xo=lambda s: (lambda ls: ls.count('o')==ls.count('x'))(s.lower())