guys, I wrote a function to test if two inputs (a and b) have the same data structure, this way:
print same_structure([1, 0, 1], [a, b, c])
#>>> True
#print same_structure([1, [0], 1], [2, 5, 3])
>>> False
#print same_structure([1, [2, [3, [4, 5]]]], ['a', ['b', ['c', ['d', 'e']]]])
>>> True
#print same_structure([1, [2, [3, [4, 5]]]], ['a', ['b', ['c', ['de']]]])
>>> False
This function has (in my implementation) to use recursion. I’m very beginner in recursion and I still have difficulty on thinking recursively. In addition, to avoid cheating the answer, I want to use my own (messy) code and through it learn to use the recursive call (using this code line: ‘same_structure return (a [i], b [e])’ properly). Could someone show how to properly use the recursion in code below?
Thanks in advance for any help!!!
def is_list(p):
return isinstance(p, list)
def same_structure(a,b):
if not is_list(a) and not is_list(b):
print '#1'
return True
else:
if is_list(a) and is_list(b):
print '#2'
if len(a) != len(b):
print '#3'
return False
if len(a) == len(b):
print '#4'
for e in range(len(a)):
print 'e = ', e, 'a[e]= ', a[e], 'b[e]=', b[e]
return same_structure(a[e], b[e])
else:
return False
The following works:
When writing recursive functions, you first need to come up with the base case, where you just return a value instead of calling any recursion. The base case here is one of the following conditions:
ais a list andbisn’t, or vice-versa: return Falseaandbare both lists, but they have different lengths: return Falseaorbare lists: return TrueIf
aandbare both lists and they have the same length, we need to now check each element of these lists recursively.zip(a, b)provides a convenient way to iterate over the elements from each list together, and if the result ofsame_structure()is False for any two sub-elements, we want the entire function to return False. This is whyall()is used, if you are unfamiliar withall()it is equivalent (but more efficient) to the following loop:Here is how you could rewrite your function without changing too much, the logic is actually very similar to my solution, but just below the
print '#4'you were returning from that loop too early: