Right Solution, but Can't Pass Exercise

For Code Challenge, Reverse Loops :slight_smile:
https://www.codecademy.com/courses/learn-python-3/lessons/python-functions-loops-cc/exercises/reversed

I have created code that comes to the right outputs, however i am not able to get past the exercise. I’m guessing there is something I have done wrong, but after trying a few different ways to do this I can’t seem to figure it out. Does anyone have any insight?

My Code:

#Write your function here

def reversed_list(lst1, lst2):
  for num in range(len(lst1)-1, -1, -1):
    for nums in lst1:
      if num == nums:
        return True
    else:
      return False


#Uncomment the lines below when your function is done
print(reversed_list([1, 2, 3], [3, 2, 1]))
print(reversed_list([1, 5, 3], [3, 2, 1]))

as the error message tells you:

reversed_list([], []) should have returned True, and it returned None

you missed an edge case, if you add this case, you will see you get None (the absence of return value).

there are also further edge cases, like this one:

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

This gives True, while its true all the numbers are in both lists, the lists are not reverse of each other.

      if num == nums:
        return True

making one comparison is not enough to determine the overall result, to be able to say that one is the reverse of the other, you have to compare all the values

you have a for-else, which I’m guessing you don’t know what it does, so it shouldn’t be in your code

aside from exiting too early, the loops don’t visit values in a suitable order

for one of the lists you don’t look at the values at all

@design9699039525
I would probably approach the question differently. I would first sort the second list i.e (lst2).
Then use the conditional statement to check if they are the same. Check the code below tell me what you think.

def reversed_list(lst1, lst2):
  if lst1 == sorted(lst2):
    return True
  else:
    return False

This approach works but there are several approaches really. Give me your opinion on this.

That would say that [1,2,3] is the reverse of [1,2,3], which it isn’t.
It would also say that [3,2,1] is not the reverse of [1,2,3] … which it is.

Being reversed isn’t related to being sorted.

You should probably write it this way instead, the if-statement is redundant:

def reversed_list(lst1, lst2):
  return lst1 == sorted(lst2)

@ionatan
Thanks for the correction. I see your point coz if we had something like [8,7,9,4] and [4,9,7,8] it wouldn’t work. I think this is an improved version of what I had written earlier.

def reversed_list(lst1, lst2):
    lst2_reverse = []
    while len(lst2) > 0:
        value = lst2.pop()
        lst2_reverse.append(value)
    return lst1 == lst2_reverse
print(reversed_list([1, 2, 3], [3, 2, 1]))
print(reversed_list([1, 5, 3], [3, 2, 1]))