Look and Say Sequence - 字符串索引超出范围

时间:2015-10-08 00:14:52

标签: python

我正在尝试在Python中实现Look and Say序列并获取错误'String index out of range'。我刚刚开始使用python,所以如果你看到任何其他语法错误,请指出它们。

def enlighten(number):
    i=0
    Final = []
    length = len(number)
    while i < length:
            Type=number[i]
            Nt=0
            while number[i]==Type:
                    Nt+=1
                    i+=1
            Final.append(Nt)
            Final.append(Type)
            Type=None
    return Final

inpoot = str(input("Enter a number:"))
for i in inpoot:
    print(enlighten(i))

2 个答案:

答案 0 :(得分:0)

while i < length:
   # ...
   while number[i]==Type:
       # ...
       i+=1

i在嵌套循环中递增,导致number[i]超出范围。

一个简单而直接的解决方法是检查嵌套循环中i的值:

while i < length:
   # ...
   while i < length and number[i]==Type:
       # ...
       i+=1

答案 1 :(得分:0)

你正在推动内循环的“i”超过字符串长度,无论如何它只是一个字符。你能描述一下你期望这个例程是如何工作的吗?你还没有让我们知道“启蒙”应该作为一种功能完成什么。

我添加了一些诊断语句,以帮助您将来跟踪代码的进度。

def enlighten(number):
    print "CHECK A", number
    i = 0
    Final = []
    length = len(number)
    print "length", length
    while i < length:
        Type = number[i]
        Nt = 0
        print "CHECK B", Type, i
        while number[i] == Type and i < length:
            print "CHECK C", number[i], Nt, i
            Nt += 1
            i += 1
        Final.append(Nt)
        Final.append(Type)
        Type = None
        print "CHECK D", Final
    return Final

inpoot = str(input("Enter a number:"))
print type(inpoot), inpoot
for i in inpoot:
    print(enlighten(i))