下面我用islower()制作了5个不同的函数。 目标是检查给定函数是否满足目的,即检查给定字符串是否包含至少一个小写。 我也附上了理由,请检查我的分析/解释是否有效。
#Example1: True
def any_lowercase1(s):
for c in s:
if c.islower():
return True
else:
return False
#Example2: False
## this function checks only the string 'c' is lower, which always returns True
def any_lowercase2(s):
for c in s:
if 'c'.islower():
return 'True'
else:
return 'False'
#Example3: False
##the result only depends on the last letter of given string
def any_lowercase3(s):
for c in s:
flag = c.islower()
return flag
#Example4: False
##Similar to Example3, this function also depends on the last character of given string
def any_lowercase4(s):
flag = False
for c in s:
flag = flag or c.islower()
return c.islower()
#Example5: False
## This function returns False if it conatains more than one Captial Letter.
def any_lowercase5(s):
for c in s:
if not c.islower():
return False
return True
print(any_lowercase4('RrR'))
#above must be true, but it returns False
答案 0 :(得分:0)
我会使用正则表达式:
>>> import re
>>> re.findall('[a-z]', 'RrR')
['r']
>>> re.findall('[a-z]', 'RRR')
[]
示例4不起作用,因为当您应该返回c.islower()
时返回flag
。
如果你需要检查哪个功能有效,哪个不行 - 用一些已知数据写一些测试:
if __name__ == '__main__':
ONLY_LOWER = ['aaa', 'a', 'hello', 'foo and bar']
NOT_LOWER = ['X', 'Xa', 'Aha', 'Try this One']
FUNCS = [any_lowercase1, any_lowercase2, any_lowercase3, any_lowercase4, any_lowercase5]
good_funcs = [f.__name__ for f in FUNCS]
for f in FUNCS:
result = True
for item in ONLY_LOWER:
if not f(item):
print("Function '<{}>' returned false for lower item '{}'".format(f.__name__, item))
if f.__name__ in good_funcs:
good_funcs.remove(f.__name__)
break
for item in NOT_LOWER:
if f(item):
print("Function '<{}>' returned true for non lower item '{}'".format(f.__name__, item))
if f.__name__ in good_funcs:
good_funcs.remove(f.__name__)
break
print("Here are function, which passed the tests: {}".format(good_funcs))
>> Function '<any_lowercase2>' returned true for non lower item 'X'
>> Function '<any_lowercase3>' returned true for non lower item 'Xa'
>> Function '<any_lowercase4>' returned true for non lower item 'Xa'
>> Function '<any_lowercase5>' returned false for lower item 'foo and bar'
>> Here are function, which passed the tests: ['any_lowercase1']