Code Signal_练习题_Are Similar?
Posted yd2018
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Code Signal_练习题_Are Similar?相关的知识,希望对你有一定的参考价值。
Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements in one of the arrays.
Given two arrays a
and b
, check whether they are similar.
Example
-
For
a = [1, 2, 3]
andb = [1, 2, 3]
, the output should beareSimilar(a, b) = true
.The arrays are equal, no need to swap any elements.
-
For
a = [1, 2, 3]
andb = [2, 1, 3]
, the output should beareSimilar(a, b) = true
.We can obtain
b
froma
by swapping2
and1
inb
. -
For
a = [1, 2, 2]
andb = [2, 1, 1]
, the output should beareSimilar(a, b) = false
.Any swap of any two elements either in
a
or inb
won‘t makea
andb
equal.
我的解答:
1 def areSimilar(a, b): 2 count = 0 3 if sorted(a) == sorted(b): 4 for i in zip(a,b): 5 if i[0] != i[1]: 6 count +=1 7 if count > 2: 8 return False 9 else: 10 return True 11 else: 12 return False
膜拜大佬:
def areSimilar(A, B): return sorted(A)==sorted(B) and sum([a!=b for a,b in zip(A,B)])<=2
以上是关于Code Signal_练习题_Are Similar?的主要内容,如果未能解决你的问题,请参考以下文章