这个RLE算法在Python中有什么问题?

时间:2018-03-19 11:17:24

标签: python python-3.x algorithm

我一段时间以前完成了这个RLE代码,而且我似乎对发生的错误视而不见。 encode()的预期输出应为'a1b2c3',但我得到的值为'None'。

def encode(text):
if not text:
    return ""
else:
    last_char = text[0]
    max_index = len(text)
    i = 1
    while i < max_index and last_char == text[i]:
        i += 1
        return last_char + str(i) + encode(text[i:])

print(encode("abbccc"))

def decode(text):
if not text:
    return ""
else:
    char = text[0]
    quantity = text[1]
    return char * int(quantity) + decode(text[2:])

print(decode("a1b2c3"))

此致

2 个答案:

答案 0 :(得分:0)

def encode(text):
last_char = text[0]
max_index = len(text)
i = 1
while i < max_index and last_char == text[i]:
    i += 1
return last_char + str(i) + encode(text[i:])

text = "abbccc"
print(encode(text))

def decode(text):
if not text:
    return ""
else:
    char = text[0]
    quantity = text[1]
    return char * int(quantity) + decode(text[2:])

text2 = "a1b2c3"
print(decode(text2))

他为什么会收到错误:last_char = text [0] IndexError:字符串索引超出范围

如果数组中的第一个值是'a'。

答案 1 :(得分:0)

问题只是缩进。

def encode(text):
    if not text:
        return ""
    else:
        last_char = text[0]
        max_index = len(text)
        i = 1
        while i < max_index and last_char == text[i]:
            i += 1
        return last_char + str(i) + encode(text[i:])

print(encode("abbccc"))

def decode(text):
    if not text:
        return ""
    else:
        char = text[0]
        quantity = text[1]
    return char * int(quantity) + decode(text[2:])

print(decode("a1b2c3"))

输出:

a1b2c3
abbccc