for for循环for python不工作

时间:2014-12-15 23:16:17

标签: python-2.7 loops for-loop

我试图实现这个功能。

def eq_chars(s,i):
"""Returns: length of sequence of equal characters starting at s[i].
Examples: eq_chars('aaaxxyx',0) is 3 and eq chars('aaaxxyx',5) is 1
Precondition: s is a string, 0 <= i < len(s).""

&#34;

到目前为止,我的代码是:

    for i in range(len(s)):
        accumulator = 0
        if s[i] == s[i+1]:
            accumulator = accumulator + 1
            return accumulator
        else:
            pass

我知道for循环开头有问题。我代表将给予我们的指数。你可以改变变量吗?我究竟做错了什么?任何帮助表示赞赏

1 个答案:

答案 0 :(得分:0)

问题是你在if语句满足时返回,并且在循环开始时你正在丢失i的值。正确的代码应该是:

def eq_chars(s, i):
    accumulator = 1
    for j in range(i, len(s) - 1):
        if s[j] == s[j+1]:
            accumulator += 1
        else:
            break
    return accumulator

此函数从给定索引开始,检查下一个字符是否与当前字符相同。如果找到匹配则会增加计数。当看到不匹配的字符时,它会停止循环并返回计数。