Python Computer Programming Write a recursive function thesa

Python Computer Programming:

Write a recursive function the_same(x, y) that returns a Boolean value indicating whether x and y (the two lists) are equal without directly comparing x == y. You can only compare the lengths of x,y and test whether individual list elements are equal. You can use only basic operations and the only function you are allowed to use is the built-in len function. You cannot make any other function calls other than the recursive call to the_same.

Hint: two lists are \"equal\" iff they are the same length and every corresponding element is the same.

Solution

//Tested on Ubuntu,Linux

Python --version is 2.7.12

/****************listCompare.py***************/

#/usr/bin/env python
#_same function compare the both list x and y recursively
#if val of x is in y the we will call _same function for
#comparing next value
#otherwise we will return False
def _same(x, y):
   for val in x:
       if val in y:
           _same(x[1:],y[1:]);
       else:
           return False;
   return True

#list values initially  
x = [1,2,3,4,\"test\",\"hello\"]
y = [1,2,3,4,\"test\",\"hello\"]
#if length of both list are different
#Then List are not Equal
#otherwise we will call _same function
if(len(x)==len(y)):
   flag=_same(x,y)
   if(flag):
       print(\'Both List are Equal\')
   else:
       print(\'Not Equal\')
else:
   print(\'Not Equal\')


/****************output*************/

anshu@anshu:~/Desktop/chegg$ python listCompare.py

Both List are Equal

Thanks a lot

If you have any query feel free and ask

Python Computer Programming: Write a recursive function the_same(x, y) that returns a Boolean value indicating whether x and y (the two lists) are equal without

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site