2014-09-28 78 views
-1

所以我要找出这个代码有什么问题,显然我没有看到任何错误,因为我刚刚学习了python。Python函数错误字符串索引超出范围

此外,当我运行该功能,它会给我一个错误"String Index out of range"

而我要测试这是否有效。

那么,什么似乎是错的,我应该如何测试它们?

def is_reverse_of(st1, st2): 

    """ 
    is_reverse_of : String String -> Boolean 
    is_reverse_of tells if one string is the reverse of another. 
    preconditions: st1 and st2 are character strings. 
    """ 
    if len(st1) != len(st2): 
     return False 
    i = 0 
    j = len(st2) 
    while j > 0: 
     if st1[i] != st2[j]: 
      return False 
     else: 
      i += 1 
      j -= 1 

    return True 

这是我到目前为止的测试

def test_is_reverse_of(): 

    """ 
    a suite of pass/fail test cases to validate that is_reverse_of works. 
    """ 
    # Complete this test function. 
    st1 = str(input("Enter the string: ")) 
    st2 = str(input("Enter the string: ")) 

    is_reverse_of(st1, st2) 
+0

检查'[j]'索引政策。尝试访问长度为len(aString)== j'的字符串的第j个元素失败,因为索引是从零开始的---'aString [0]'...'aString [len-1 ]' – user3666197 2014-09-28 01:02:07

+0

'input'已经是一个字符串,所以不需要转换和'如果st1 [i]!= st2 [j-1]:'将解决你的索引错误 – 2014-09-28 01:09:16

回答

1

该指数是基于0的,所以它是从0到LEN(STR2) - 1,不LEN(STR2) 。您可以轻松地做简单的解决这个问题:

j = len(st2) - 1 

顺便说一句,你真的只需要一个指数,eitehr i或j,因为其他人可以很容易地计算出:

def is_reverse_of(st1, st2): 
    if len(st1) != len(st2): 
     return False 
    l = len(st1)  
    for i in range(0, l): 
     if st1[i] != st2[l - 1 - i]: 
      return False 
    return True 
+0

谢谢你的明确答案。我已经修复它并运行该功能,它没有错误地工作。但是,现在我应该如何开始测试函数是否有效(如果它确实表明这些字符串彼此相反) – Eric 2014-09-28 01:35:21

+0

尝试不同的情况并观察结果,例如:print(is_reverse_of(“ab “,”ba“))应该打印为真; print(is_reverse_of(“ab”,“bac”))应该打印False等。 – 2014-09-28 01:37:42

+0

太棒了!它工作正常。谢谢 – Eric 2014-09-28 01:41:51