Define a procedure, same_structure, that takes two inputs. It should output
True
if the lists have the same structure, and False
otherwise. Two values, p and q have the same structure if:
Neither p or q is a list.
Both p and q are lists, they have the same number of elements, and each
element of p has the same structure as the corresponding element of q.
EDIT: To make the picture clear the following are the expected output
same_structure([1, 0, 1], [2, 1, 2])
---> True
same_structure([1, [0], 1], [2, 5, 3])
---> False
same_structure([1, [2, [3, [4, 5]]]], ['a', ['b', ['c', ['d', 'e']]]])
---> True
same_structure([1, [2, [3, [4, 5]]]], ['a', ['b', ['c', ['de']]]])
---> False
I thought recursion would be best to solve this problem in python I have come up with the following code but its not working.
def is_list(p):
return isinstance(p, list)
def same_structure(a,b):
if not is_list(a) and not is_list(b):
return True
elif is_list(a) and is_list(b):
if len(a) == len(b):
same_structure(a[1:],b[1:])
else:
return False
Method 6: Use symmetric_difference to Find the Difference Between Two Lists in Python. The elements that are either in the first set or the second set are returned using the symmetric_difference() technique. The intersection, unlike the shared items of the two sets, is not returned by this technique.
Using Counter() , we usually are able to get frequency of each element in list, checking for it, for both the list, we can check if two lists are identical or not. But this method also ignores the ordering of the elements in the list and only takes into account the frequency of elements.
The difference between two lists (say list1 and list2) can be found using the following simple function. By Using the above function, the difference can be found using diff(temp2, temp1) or diff(temp1, temp2) . Both will give the result ['Four', 'Three'] .
Instead of same_structure(a[1:],b[1:])
, you need to check item pair of a and b one by one
def is_list(p):
return isinstance(p, list)
def same_structure(a, b):
if not is_list(a) and not is_list(b):
return True
elif (is_list(a) and is_list(b)) and (len(a) == len(b)):
return all(map(same_structure, a, b)) # Here
return False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With