为什么我的 Python 测试用例在这个编码挑战中失败了?



这是问题所在:

给定一个字符串,返回 子字符串长度 2 出现在字符串中,也显示为最后 2 个字符 的字符串,因此"hixxxhi"产生 1(我们不会计算结尾 子字符串(。

last2('Hixxhi'( → 1 last2('xaxxaxaxx'( → 1 last2('axxxaaxx'( → 2

我的解决方案::

def last2(str):
excl_last2 = str[:-2];
list_excl_last2=[];
for i in range(len(excl_last2)-1):
list_excl_last2.append(excl_last2[i:i+2]);
count = 0;
for i in list_excl_last2:
if str[-2:] == i:
count = count + 1;
return count;

它通过所有测试用例,除了如果str = 'xxxx'的测试用例。我的程序返回 1。预期输出为 2。为什么会这样?

在扫描字符串以查找匹配项之前,要从字符串中删除最后两个字符。所以excl_last2 = 'xx'在那个测试用例中,那里只有一个匹配项。

您应该只删除最后一个字符,而不是最后两个字符。

顺便说一句,您不应该使用标准函数的名称作为变量名称。strcount是标准的内置函数

您可以在第一个循环中进行计数,而不是构造子字符串列表。

def last2(string):
excl_last1 = string[:-1];
last2 = string[-2:]
ct = 0
for i in range(len(excl_last2)-1):
if excl_last2[i:i+2] == last2:
ct += 1
return ct  
def last2(str):
last2chars = str[len(str)-2:];
count=0;
for i in range(len(str)-2):
if str[i:i+2]==last2chars:
count = count + 1;  
return count;

上面的代码通过了所有测试用例。感谢巴马尔的逻辑 失败测试用例的说明;根据建议我修改了它,现在它似乎通过了所有测试用例。