-3

I want to check whether there are duplicate elements which is more than 0 in an array list.

if [1,0,0,0,1,2] = true

if [0,0,0,0,0,0] = false 

How can I get this result?

Sangbok Lee
  • 2,132
  • 3
  • 15
  • 33
Chathurika
  • 419
  • 2
  • 6
  • 18

2 Answers2

0

I guess OP wants to handle natural numbers only. Try this:

def is_duplicated_natural_numbers(input):
    # make it >0
    natural_numbers_list = list(filter(lambda x: x > 0, input))

    # remove duplicates
    set_list = list(set(natural_numbers_list))

    # if natural_numbers_list == set_list, no natural numbers duplicates
    return natural_numbers_list != set_list

print(is_duplicated_natural_numbers([1,0,0,0,1,2]))  # True
print(is_duplicated_natural_numbers([0,0,0,0,0,0]))  # False
print(is_duplicated_natural_numbers([1,2,3,4,5,1]))  # True
Sangbok Lee
  • 2,132
  • 3
  • 15
  • 33
-1

Use a dictionary to keep a count of elements and if an element occurs twice (which is not zero) then your answer is true so just break from the loop.

Try This :

l = [0,0,0,0]
dic = {}
flag = False
for i in l:
    if i in dic:
        dic[i]+=1
        if dic[i]>1 and i!=0:
            flag = True
            break
    else:
        dic[i] = 1
print flag

Note : Better ways are there but this one is really simple to understand.

Karan Nagpal
  • 341
  • 2
  • 10