开发者社区 问答 正文

我的python代码如何越界?

我一直在尝试将字符串(例如:aabbbacc)编码为a2b3a1c2之类的东西,这是我尝试过的代码:

string_value = "aabbbacc"
temp_string = ""
for i in range(0, len(string_value)):
    if i != len(string_value) or i > len(string_value):
        temp_count = 1
        while string_value[i] == string_value[i+1]:
            temp_count += 1
            i += 1
        temp_string += string_value[i] + str(temp_count)
print(temp_string)

问题是即使我添加了一个if条件以防止发生超出范围的问题,我仍然会收到错误消息

Traceback (most recent call last):
  File "C:run_length_encoding.py", line 6, in <module>
    while string_value[i] == string_value[i+1]:
IndexError: string index out of range

我也尝试过

string_value = "aabbbacc"
temp_string = ""
for i in range(0, len(string_value)):
    count = 1
    while string_value[i] == string_value[i+1]:
        count += 1
        i += 1
        if i == len(string_value):
            break
    temp_string += string_value[i]+ str(count)
print(temp_string)

现在,我知道可能有更好的方法来解决此问题,但是我试图理解为什么我遇到了超出范围的异常,即使我有一个if条件可以阻止它,但在逻辑的哪一部分呢?出问题了请解释...

问题来源:stackoverflow

展开
收起
is大龙 2020-03-23 20:57:11 558 分享 版权
1 条回答
写回答
取消 提交回答
  • 问题在这里:

    for i in range(0, len(string_value)): # if i is the last index of the string
        count = 1
        while string_value[i] == string_value[i+1]: # i+1 is now out of bounds
    

    避免越界的最简单方法是根本不索引字符串:

    def encode(s):
        if s == '':   # handle empty string
            return s
        current = s[0]  # start with first character (won't fail since we checked for empty)
        count = 1
        temp = ''
        for c in s[1:]:  # iterate through remaining characters (string slicing won't fail)
            if current == c:
                count += 1
            else: # character changed, output count and reset current character and count
                temp += f'{current}{count}'
                current = c
                count = 1
        temp += f'{current}{count}'  # output last count accumulated
        return temp
    
    print(encode('aabbbacc'))
    print(encode(''))
    print(encode('a'))
    print(encode('abc'))
    print(encode('abb'))
    

    输出:

    a2b3a1c2
    
    a1
    a1b1c1
    a1b2
    

    回答来源:stackoverflow

    2020-03-23 20:57:17
    赞同 展开评论
问答分类:
问答标签:
问答地址: