Hi Sir/ Ma’am, i am not understanding what i did wrong in my code. When i am submitting the answer the is_reversed variable is coming red. Also the answer given is not understood. Help will be appreciated in both, thanks. Struggling.
for i in range(len(values1)):
if values1[i] == values2[-i-1]:
is_reversed = True
is_reversed = False
What actually happened:
You should stop iteration once you find that one of the element is not matched.
is_reversed = False
Without break it will eventually end up with result of last elements comparison.
values1 = [1,2,3]
values2 = [3,4,1]
As per your logic we will iterate over
value2 from backward list. So
First iteration we will check first element of
value1 and first from last element of
1 == 1 yes then we will set it flag
Second iteration we will check second element of
value1 and second last of
2 == 4 yes then we will set it flag
Now we know it is not matching so we can say list is not reversed. and we can stop iteration further from here using
but if we don’t stop here it will go for next element third iteration
Third iteration we will check third element of
value1 and third from last element of
3 == 3 yes then we will set it flag
So here it changed from
True so as i said we will eventually end up with result of last elements comparison.
it worked. Can you explain more i didnt understood. Thanks for quick reply
I tried your code on the mentioned screen, as below:
Except that the logic needs to be reworked because on every comparison, the is_reversed variable is getting overwritten. The final value of is_reversed would correspond to the last elements in each list. So, you can either print the is_reversed variable at each loop iteration or keep a count of the number of mismatches.
@niranjana.r.iisc Thank you for your response
I have updated my answer and add some explanation. Hope it will help. I would suggest you to do debugging of your code on paper.
i will try to understand your explanation
It helped. Thanks a ton Also in the first solution given by dataquest they first printed is_reversed = true and then said that if the value is not equal then false. Did i got that right? We can do as per my code too right?
I did something I considered easier and shorter. I tested in the practice program an it worked. This is my program to check if one list is the reversed of another one:
values1 = [80, 109, 111, 109, 94, 93, 108, 107, 81, 111, 101, 114, 102, 81, 107, 120, 108, 92, 113, 119, 97]
values2 = [97, 119, 113, 92, 108, 120, 107, 81, 102, 114, 110, 111, 81, 107, 108, 93, 94, 109, 111, 109, 80]
is_reversed = values1 == list(reversed(values2))
if is_reversed is True: