python - CodingBat 热身 2 Python Last2

标签 python

我想我已经解决了这个问题,但是当我在 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/

相关文章:

python - Python 中的联系人跟踪 - 使用时间序列

python - 我需要帮助用立方体形成一个圆圈,使用 blender 2.69 和 python 引擎

Python - 操作列表以创建另一个列表

javascript - 如何使用 javascript 客户端设置 Python 服务器端

Javascript 和 Django 'static' 模板标签

python - 值错误 : First argument must be a sequence ----> Scatter Plot Python

python - python如何判断一个参数是引用还是值?

python - 按数据类型对python字典进行排序

python - 按 DataFrame 的另一列移动列分组的值

python - 使用鼠标悬停在 2D 点图上查找 numpy 数组中的行/位置