代码来自CodingBat,问题是:如果字符串“ cat”和“ dog”在给定字符串中出现相同的次数,则返回True。
我有解决方案,但它指出字符串索引超出范围。由于我是python新手,所以我不太了解这意味着什么。
def cat_dog(str):
dogCount = 0
catCount = 0
length = len(str)
if length > 6:
for i in range(length-1):
if str[i]== 'd' and str[i+1]== 'o' and str[i+2]== 'g':
dogCount +=1
elif str[i]== 'c' and str[i+1]== 'a' and str[i+2]== 't':
catCount +=1
else:
return False
if dogCount == catCount:
return True
else:
return False
根据函数结果期望是对还是错
答案 0 :(得分:0)
字符串索引超出范围错误表示您正在尝试访问超出字符串长度的字母。这是在您的for循环中发生的,因为当i = length - 2
,str[i+2]
变成str[length]
时,它超出了字符串的长度。另外,您应该将if length > 6
更改为if length >= 6
。尝试以下代码:
def cat_dog(string):
dogCount = 0
catCount = 0
length = len(string)
if length >= 6:
for i in range(length-2):
if string[i]== 'd' and string[i+1]== 'o' and string[i+2]== 'g':
dogCount +=1
elif string[i]== 'c' and string[i+1]== 'a' and string[i+2]== 't':
catCount +=1
else:
return False
if dogCount == catCount:
return True
else:
return False
答案 1 :(得分:0)
一种可能的解决方案是连续检查该字符串,以查看它是否包含替换第一个匹配项的单词中的一个,直到不再存在为止:
def cat_dog(string):
dogCount = 0
catCount = 0
while "dog" in string:
dogCount += 1
string = string.replace("dog", "", 1)
while "cat" in string:
catCount += 1
string = string.replace("cat", "", 1)
if dogCount == catCount:
return True
else:
return False