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] and b = [1, 2, 3], the output should be
      areSimilar(a, b) = true.

      The arrays are equal, no need to swap any elements.

    • For a = [1, 2, 3] and b = [2, 1, 3], the output should be
      areSimilar(a, b) = true.

      We can obtain b from a by swapping 2 and 1 in b.

    • For a = [1, 2, 2] and b = [2, 1, 1], the output should be
      areSimilar(a, b) = false.

      Any swap of any two elements either in a or in b won't make aand b equal.

我的解答:

 def areSimilar(a, b):
count = 0
if sorted(a) == sorted(b):
for i in zip(a,b):
if i[0] != i[1]:
count +=1
if count > 2:
return False
else:
return True
else:
return False

膜拜大佬:

def areSimilar(A, B):
return sorted(A)==sorted(B) and sum([a!=b for a,b in zip(A,B)])<=2
上一篇:Book for Opencv


下一篇:Salt 与Salt API配置