我想我已经解决了这个问题,但是当我在 pythonfiddle.com 或 Canopy 上运行它时,什么也没有出现。
问题是:
Given a string, return the count of the number of times that a substring length 2 appears in the string and also as the last 2 chars of the string, so "hixxxhi" yields 1 (we won't count the end substring).
last2('hixxhi') → 1 last2('xaxxaxaxx') → 1 last2('axxxaaxx') → 2
我的解决方案是:
def last2(str):
test2 = str[-2:]
start = 0
count = 0
while True:
if str.find(test2, start, -2) > 0:
count +=1
start = str.find(test2, start, -2) + 1
else:
break
return count
当我调用函数last2
时,我什么也没得到。我有什么遗漏的吗?
最佳答案
如果未找到匹配项,
str.find()
将返回 -1
。如果在字符串的开始处找到匹配项,则返回0
,但您的测试条件排除了这种情况。
if str.find(test2, start, -1) > 0:
您也想匹配0
:
if str.find(test2, start, -2) >= 0:
您可以避免在此处使用 str.find()
两次,并且您希望允许最后一个字符也计数(xxxx
除了匹配最后两个字符之外,还有两次 xx
)。最后但并非最不重要的一点是,如果字符串的长度短于三,则永远不会有任何匹配:
def last2(value):
if len(value) < 3:
return 0
test2 = value[-2:]
start = 0
count = 0
while True:
index = value.find(test2, start, -1)
if index == -1:
break
count +=1
start = index + 1
return count
我也避免在这里隐藏内置的 str()
函数。
演示:
>>> last2('hixxhi')
1
>>> last2('xaxxaxaxx')
1
>>> last2('axxxaaxx')
2
关于python - CodingBat 热身 2 Python Last2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20587007/