Look and Say序列字符串索引超出范围

2024-06-24 13:01:42 发布

您现在位置: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))

Tags: andnumberstringtype错误序列lengthfinal
2条回答

你把内部循环的“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))
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

相关问题 更多 >