5

定义一个过程,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
4

5 回答 5

6

而不是,您需要一个一个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
于 2012-04-09T15:43:03.050 回答
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:])
于 2012-04-09T15:24:12.077 回答
3

递归是一个好主意,但不是您建议的方式。首先(这可能只是一个错字),你实际上并没有在这里返回任何东西:

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

希望这可以帮助。

于 2012-04-09T15:22:53.590 回答
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))
于 2012-04-09T15:46:09.120 回答
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))
于 2017-02-13T14:56:38.737 回答