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

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) —
推荐阅读:绿茶、红茶、青茶、黑茶、白茶和黄茶 奶茶多添加奶精 长期食用会引发心脏病 奶茶调查:街头奶茶店调香味多用奶精 适合秋天食用的养肺食谱可滋阴润肺 哪些食物可以起到止咳润肺的作用 食物的禁忌:中医如何区分食物的寒热性 味道鲜美营养丰富的黑木耳最佳吃法 怎样食用萝卜可以治咳嗽使症状缓解 柚子营养价值高多吃对健康大有益处 美食“扬州炒饭”新标准公布了制作方法
- 评论列表
-
- 添加评论