字符串索引超出范围DNA回文结构

时间:2016-10-28 18:33:33

标签: python string range out

我无法弄清楚为什么字符串超出范围,以及如何修复它。 如果我知道这个问题,我可以尝试修复它,但我不明白这个问题 以下是代码:

def get_odd_palindrome_at(s1, number):
    '''(str, int) -> str
    precondition: int is valid index in s1
        return str of longest odd palindrome, of which the middle is number. 
    '''

    if s1[number-1] != s1[number+1]:
        return s1[int]
    num =  1 
    while num < len(s1):
        if s1[number-num] == s1[number+num]: 
            num= num +1 
    return s1[number-num: number+num+1] 

get_odd_palindrome_at("AGTGAT", 2)

2 个答案:

答案 0 :(得分:0)

我看到两个问题。

在语句return s1[int]中,int不是s1的有效索引

在循环中,num与len(s1)-1一样高。在声明的这一点上

  

如果s1 [number-num] == s1 [number + num]:

number+num超出了范围。

答案 1 :(得分:0)

您必须调整2个命令才能正确检查索引是否在边界内,并修复1个错误:

而不是

    if s1[number-1] != s1[number+1]:         # number + 1 may be too large
        return s1[int]                       # it is error

使用

    if number + 1 >= len(s1)  or  s1[number-1] != s1[number+1]:
        return s1[number]

而不是

    while num < len(s1):                     # it isn't sufficient condition
        if s1[number-num] == s1[number+num]: # it is OK; only for context

使用更复杂但正确的条件

    while number - num >= 0  and  number + num <= len(s1) - 1:
        if s1[number-num] == s1[number+num]:

所以你的完整代码将是(我添加了一些空行)

def get_odd_palindrome_at(s1, number):
    '''(str, int) -> str
    precondition: int is valid index in s1
        return str of longest odd palindrome, of which the middle is number. 
    '''

    if number + 1 > len(s1) - 1  or  s1[number-1] != s1[number+1]:
        return s1[number]

    num =  1

    while number - num >= 0  and  number + num <= len(s1) - 1:
        if s1[number-num] == s1[number+num]: 
            num= num +1
            print(number, num)
    return s1[number-num: number+num+1] 

get_odd_palindrome_at("AGTGAT", 2)