0
repeat=[1,4,5,6,7,8,9,9,1,5,7,7]

how to check if there are any duplicates 2 or more using boolean operators with python. Here is my code

repeat = set()
for x in one_sample:
    if x in repeat: 
        return True
    repeat.add(x)
return False
print(repeat)
Georgy
  • 12,464
  • 7
  • 65
  • 73

3 Answers3

1

Code showing if there are duplicates and their values if there are:

Try it online!

l = [1,4,5,6,7,8,9,9,1,5,7,7]
sl = sorted(l)
has_dups = any(f == s for f, s in zip(sl[:-1], sl[1:]))
dups_vals = sorted(set(f for f, s in zip(sl[:-1], sl[1:]) if f == s))
print('has dups:', has_dups, ', dups values:', dups_vals)

Outputs:

has dups: True , dups values: [1, 5, 7, 9]

Code works lazily, i.e. it sets has_dups to True (found duplicate) as soon as the very first duplicate is found in sorted array.

If input array is very large, then numpy can be used which is magnitude faster than pure Python. Next code implements same task using numpy (numpy needs to be installed once python -m pip install numpy):

Try it online!

import numpy as np
l = [1,4,5,6,7,8,9,9,1,5,7,7]
sa = np.sort(l)
has_dups = np.any(sa[:-1] == sa[1:])
dups_vals = sa[np.append(np.diff(
    np.insert((sa[:-1] == sa[1:]).astype(np.int8), 0, 0)
) == 1, False)]
print('has dups:', has_dups, ', dups values:', dups_vals)

Output is same:

has dups: True , dups values: [1 5 7 9]

And another even simpler numpy solution:

import numpy as np
l = [1,4,5,6,7,8,9,9,1,5,7,7]
vals, cnts = np.unique(l, return_counts = True)
has_dups = np.any(cnts > 1)
dups_vals = vals[cnts > 1]
print('has dups:', has_dups, ', dups values:', dups_vals)

Also just checking if there are any duplicates can be done using simple next code with set():

l = [1,4,5,6,7,8,9,9,1,5,7,7]
has_dups = len(set(l)) < len(l)
print('has dups:', has_dups)

outputs

has dups: True
Arty
  • 14,883
  • 6
  • 36
  • 69
1

As you asked for boolean operators

repeat=[1,4,5,6,7,8,9,9,1,5,7,7]
repeat = sorted(repeat)
for i in range(len(repeat)-1):
    if repeat[i]==repeat[i+1]:
        return True
return False

Complexity O(nlog(n))

7u5h4r
  • 459
  • 3
  • 10
-1
def isDup(arrayList):   
  x={}
  for i in arrayList:
    if i in x:
      return True
    x[i]=1
  return False
Gopi krishna
  • 308
  • 1
  • 9
  • Why not just use a `set` instead of a dict, if your values have no meaning? Then, how is that different from OP's code? – Tomerikoo Sep 27 '20 at 15:21