定义一个带有两个输入的过程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
答案 0 :(得分:5)
你错过了一个案子,在第二个案件中忘了回来。请注意,没有必要明确地比较列表的长度,因为第一种情况负责这一点 - 如果其中一个列表为空而另一个列表不是,那是因为一个列表的元素少于另一个列表:
def same_structure(a, b):
if a == [] or b == []: # one of the lists is empty
return a == b # are both of the lists empty?
elif is_list(a[0]) != is_list(b[0]):
return False # one of the elements is a list and the other is not
elif not is_list(a[0]): # neither element is a list
return same_structure(a[1:], b[1:])
else: # both elements are lists
return same_structure(a[0], b[0]) and same_structure(a[1:], b[1:])
答案 1 :(得分:5)
而不是same_structure(a[1:],b[1:])
,您需要逐个检查a和b 的项目对
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
答案 2 :(得分:3)
递归会是一个好主意,但不是你建议的方式。首先(这可能只是一个错字),你实际上没有在这里返回任何东西:
if len(a) == len(b):
same_structure(a[1:],b[1:])
其次,你应该递归地处理每个元素,而不是每个子列表。即:
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
希望这有帮助。
答案 3 :(得分:1)
由于规范说输入是两个列表,您可以在不进一步检查的情况下迭代函数内的列表,并且只有在遇到子列表时才进行递归调用:
def same_structure(a, b):
if len(a) != len(b):
return False
return all(is_list(x) and is_list(y) and same_structure(x, y) or
not is_list(x) and not is_list(y)
for x, y in zip(a, b))
答案 4 :(得分:0)
您也可以尝试这种方式,检查两个列表的类型&两个列表的长度 并以递归方式对两个列表的子列表执行此操作。
def same_structure(a,b):
return isinstance(a, list) and isinstance(b, list) and len(a) == len(b)
and all(same_structure_as(c, d) for c, d in zip(a, b) if isinstance(c, list))