How to Check if Array/List Contains Duplicate Numbers or Strings

  • 时间:2020-09-18 17:39:21
  • 分类:网络文摘
  • 阅读:132 次
python-300x101 How to Check if Array/List Contains Duplicate Numbers or Strings in Python using Set? python

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) —

推荐阅读:
wordpress插件:WP-China-Yes 切换WP站点与官方通信至国内节点解决后台更新429错误  一段代码轻松解决wordpress定时发布失败的问题  WordPress官网打不开 出现 429 Too Many Request 的原因  下载更新wordpress程序及插件的方法  禁用wordpress4.4+版本自动生成768w像素缩略图功能  自动为wordpress文章图片添加alt属性和title属性  如何为WordPress导航菜单、标签、出站等链接添加nofollow标签属性  如何设置WordPress的RSS feed更新频率  利用WordPress开发者调试模式解决PHP500内部服务器错误  正确屏蔽 WordPress 版本号的代码 
评论列表
添加评论