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
Recursion would be a good idea, but not the way you’ve suggested it. First off (and this may be only a typo), you don’t actually return anything here:
Second, you should recursively deal with each element, not each sublist. ie.:
Hope this helps.