Skip to content
Advertisement

is_reverse “second” error in Think Python

There is an is_reverse program in Think Python as follows:

def is_reverse(word1, word2):
    if len(word1) != len(word2):
        return False

    i = 0
    j = len(word2) - 1

    while j > 0:
        print(i, j)
        if word1[i] != word2[j]:
            return False
        i = i + 1
        j = j - 1
    return True

The author asks to figure out an error in it which I am unable to after much brainstorming.

The program works just fine and returns this:

0  3
1  2
2  1
True

The error pertains to this output. Please help me figure it out.

Advertisement

Answer

The function suppose to check if word1 is reserve of word2 (I think, please post what you expect the function to do next time)

The function does not check final word and beginning word. It does not check word1[-1] (last character) and word2[0] (first character)

w1 = 'Dogx'
w2 = 'ggoD'
print (is_reverse(w1, w2))

The problem is here:

while j > 0:

The loop terminate before checking word2[0]. I suggest add =. THus, change the condition to:

while j >= 0:
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement