【发布时间】:2019-07-03 18:47:04
【问题描述】:
代码来自 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
根据函数结果预测真或假
【问题讨论】:
-
你调用
str[i+2]并且你的循环上升到length-1所以这就是你收到错误的原因 -
不要使用
str作为变量。这是一个python关键字
标签: python python-3.x