Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 字符串索引超出范围DNA回文组_Python_String_Range_Out - Fatal编程技术网

Python 字符串索引超出范围DNA回文组

Python 字符串索引超出范围DNA回文组,python,string,range,out,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.

我不明白为什么字符串超出范围,以及如何修复它。 如果我知道问题所在,我可以尝试解决它,但我不理解问题所在 代码如下:

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)
def get_奇数_回文_at(s1,数字):
''(str,int)->str
前提条件:int是s1中的有效索引
返回最长奇数回文的str,中间是数字。
'''
如果s1[1号]!=s1[编号+1]:
返回s1[int]
num=1
当num
我发现两个问题

在语句
returns1[int]
int不是s1的有效索引

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

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


number+num
超出范围。

您必须调整2个命令以正确检查索引是否在范围内,并修复1个错误:

而不是

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

而不是

    while num < len(s1):                     # it isn't sufficient condition
        if s1[number-num] == s1[number+num]: # it is OK; only for context
whilenum
使用更复杂但正确的条件

    while number - num >= 0  and  number + num <= len(s1) - 1:
        if s1[number-num] == s1[number+num]:
而number-num>=0和number+num len(s1)-1或s1[number-1]!=s1[编号+1]:
返回s1[编号]
num=1

当number-num>=0且此处的number+num>s1[number-num:number+num+1]时,检查此时的num是什么。什么数字加上num+1是因为我打赌它比len(s1)大。
    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)