伙计们,我写了一个函数来测试两个输入(a和b)是否具有相同的数据结构,这样:
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
这个函数(在我的实现中)使用递归。我是递归的初学者,我仍然难以递归思考。另外,为了避免欺骗答案,我想使用我自己的(凌乱的)代码,并通过它学习正确使用递归调用(使用此代码行:'same_structure return (a [i], b [e])' )。有人可以展示如何在下面的代码中正确使用递归吗?提前感谢您的帮助!!!
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