题目
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)