博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Code Signal_练习题_Are Similar?
阅读量:6909 次
发布时间:2019-06-27

本文共 1075 字,大约阅读时间需要 3 分钟。

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 True11     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

你可能感兴趣的文章
hug and Compression Resistance
查看>>
sql server 2008分页
查看>>
lintcode:Pow(x, n)
查看>>
WebService中使用Aspose.Cells.dll
查看>>
Android菜鸟的成长笔记(28)——Google官方对Andoird 2.x提供的ActionBar支持
查看>>
【转载】装饰模式与代理模式的区别
查看>>
Persona——Web人物角色介绍
查看>>
一个三年工作经验的软件工程师的经验之谈
查看>>
Keepalived+Redis高可用部署(第二版)
查看>>
理解Linux中断 (3)【转】
查看>>
3 hql语法及自定义函数(含array、map讲解) + hive的java api
查看>>
欢迎各位技术牛人增加Swift QQ群:343549891
查看>>
Linux使用imagemagick的convert命令压缩图片、节省服务器空间
查看>>
selenium测试(Java)-- 显式等待(九)
查看>>
MySQL 5.7 mysqlpump 备份工具说明
查看>>
Entity Framework Core 之数据库迁移
查看>>
ssh的用户配置文件config管理ssh会话
查看>>
安全过滤函数
查看>>
C#学习记录二:高级数据存储方式
查看>>
【162】一个程序只能运行一个
查看>>