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?
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?
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
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.