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

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的内容素材和文章构思从哪里获取?(上篇) seo专家告诉你,新网站怎么做网站优化 企业做Google SEO如何用内链优化来提高排名 建网站赚钱注意事项 别怪我没提醒你 自己建网站可以挣钱吗?做个人网站赚钱你必须要掌握的基础经验 网站赚钱 有时候就是那么简单 网上“复制”项目容易又免费 “粘贴”赚钱怎么那么简单 2020年网站赚钱应该怎么操作? 如果我们会做网站 有这个技能应该怎么赚钱? 美丽的厦门作文400字
- 评论列表
-
- 添加评论