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.

 

 

我的解答:

 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
View Code

 

转载于:https://www.cnblogs.com/BlameKidd/p/9363203.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值