-4

I'm trying to solve the following:

Write a recursive function: isEqual(list1, list2) that returns a Boolean value indicating whether the two lists are equal without directly comparing list1 == list2. You may only compare the lengths of the lists and test whether individual list elements are equal. [hint: two lists are "equal" iff they are the same length and every corresponding element is the same]

This is what is have so far, but I am stuck. Any help out there?

def isEqual(list1, list2):
    if len(list1) and len(list2) < 1:
        return True
    elif len(list1) == len(list2) and list1[-1] == list2[-1]:
        isEqual(list1[:-1], list2[:-1]) + isEqual 
        return True
    else:
        return False
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
Aaron
  • 11
  • 3

1 Answers1

0

This doesn't work:

if len(list1) and len(list2) < 1:

This is asking:

if (len(list1)) and (len(list2) < 1): 

Can you see the difference? What you're trying to write is:

if len(list1) < 1 and len(list2) < 1:

This can be shortened to:

if not list1 and not list2:

Because empty lists are false (and non-empty lists are true).

You have the right idea, but your execution is wrong. You're calling the function on the two remainder lists correctly, but you're doing some weird stuff that you don't need to.

isEqual(list1[:-1], list2[:-1]) + isEqual 
return True

should just be

return isEqual(list1[:-1], list2[:-1])

Because if the lists are the same length, and the trailing elements are equal then the lists are equal iff their list[:-1] are equal.

As a side note, most of the time people compare the first elements, then the second and so on. Is there any particular reason you're starting from the ends of the lists?

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96