Home > database >  Why this code is wrong? It provides the wrong answer
Why this code is wrong? It provides the wrong answer

Time:11-16

def reversed_list(lst1, lst2):
  for index in range(len(lst1)):
    if lst1[index] != lst2[len(lst2) - 1- index]:
      return False
    else: 
      return True

It should copmare first element of the lst1 and the last element of lst2. When I run with next comands:

print(reversed_list([1, 2, 3], [3, 2, 1]))
print(reversed_list([1, 5, 3], [3, 2, 1]))

It returns True, however second time should be False

CodePudding user response:

return immediately stops execution of the function, so your function only tests whether the first element of lst1 is equal to the last element of lst2. This is the correct thing to do if they don't match, but if they do match, you should continue your comparison.

CodePudding user response:

def reversed_list(lst1, lst2):
    for index in range(len(lst1)):
        if lst1[index] != lst2[len(lst2) - 1- index]:
              return False
    return True
  • Related