How to Check if Array/List Contains Duplicate Numbers or Strings
- 时间:2020-09-18 17:39:21
- 分类:网络文摘
- 阅读:137 次

python
In Python, we can check if an array or list contains duplicate items using the following one-liner function.
1 2 | def contain_duplicates(list): return len(set(list)) != len(list) |
def contain_duplicates(list):
return len(set(list)) != len(list)The idea is to convert the list/array to set, then we can use the len function to get the sizes of the set and the original list/array. If they are both equal, then the array or list does not contain any duplicate items.
1 2 3 4 5 6 7 8 | >>> contain_duplicates([1,2,3,4]) False >>> contain_duplicates([1,2,3,4,2]) True >>> contain_duplicates(["aa", "bb"]) False >>> contain_duplicates(["aa", "bb", "aa"]) True |
>>> contain_duplicates([1,2,3,4]) False >>> contain_duplicates([1,2,3,4,2]) True >>> contain_duplicates(["aa", "bb"]) False >>> contain_duplicates(["aa", "bb", "aa"]) True
Alternatively, you can use the following naive solution based on set.
1 2 3 4 5 6 7 | def contain_duplicates(list): data = set() for i in list: if i in data: return True data.add(i) return False |
def contain_duplicates(list):
data = set()
for i in list:
if i in data:
return True
data.add(i)
return False The time complexity is O(N) and the space requirement is O(N) as well given the size of the list is N.
–EOF (The Ultimate Computing & Technology Blog) —
推荐阅读:内容页关键词布局优化解析 中小企业需求在改变:SEO从业者需要顺应潮流 深度解析搜索引擎蜘蛛工作的原理 外贸网站建设不要忽视这6个网站设计操作 百度不再支持sitemapXML地图文档 站群推广的优点,SEO站群爆炸流量 谷歌外链用自动化工具发,真的靠谱吗 我的宝贝—《小学生之友》 写人作文娘是儿的天作文1200字 春日寻芳小学作文
- 评论列表
-
- 添加评论