定义一个过程same_structure,它需要两个输入。它应该输出
如果列表具有相同的结构,则为True
,并且为False
除此以外。如果满足以下两个条件,则p和q具有相同的结构:
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.
编辑:为了使图片清晰,以下是预期的输出
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
我认为递归将是解决python中这个问题的最好方法,我想出了以下代码,但它不起作用。
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
最佳答案
递归将是一个好主意,但不是您建议的方式。首先(这可能只是拼写错误),您实际上并没有在这里返回任何内容:
if len(a) == len(b):
same_structure(a[1:],b[1:])
其次,您应该递归处理每个元素,而不是每个子列表。 IE。:
if len(a) == len(b):
for i in range(len(a)):
if not same_structure(a[i], b[i]):
return False
return True
else:
return False
希望这可以帮助。