每日kata~12~Nesting Structure Comparison

题目

Nesting Structure Comparison
Complete the function/method (depending on the language) to return true/True when its argument is an array that has the same nesting structure as the first array.

For example:

# should return True
same_structure_as([ 1, 1, 1 ], [ 2, 2, 2 ] )
same_structure_as([ 1, [ 1, 1 ] ], [ 2, [ 2, 2 ] ] )

# should return False 
same_structure_as([ 1, [ 1, 1 ] ], [ [ 2, 2 ], 2 ] )
same_structure_as([ 1, [ 1, 1 ] ], [ [ 2 ], 2 ] )

# should return True
same_structure_as([ [ [ ], [ ] ] ], [ [ [ ], [ ] ] ] )

# should return False
same_structure_as([ [ [ ], [ ] ] ], [ [ 1, 1 ] ] )

解法

递归大法!!!

def same_structure_as(original,other):
    #your code here
    if isinstance(original,list) and isinstance(other,list):
        if len(original)==len(other):
            for i,j in zip(original,other):
                    if not same_structure_as(i,j):
                        return False
            else:
                return True
        else:
            return False
    elif isinstance(original,list)!=isinstance(other,list):
        return False
    else:
        return True

大神的解法

for...else...
当for循环中迭代对象循环完毕,即待迭代对象为空时
1、如有break,则不走else
2、如没有break,则走else

def same_structure_as(original,other):
    if isinstance(original, list) and isinstance(other, list) and len(original) == len(other):
        for o1, o2 in zip(original, other):
            if not same_structure_as(o1, o2): return False
        else: return True
    else: return not isinstance(original, list) and not isinstance(other, list)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。