-5

I'm trying to write this program but I keep facing an issue I need to see if: array import numpy as np A = [1,2,3,4,5,6,20,40,2,4,5]

if:

    print = "all elements are different"

else:

return;

"false elements match"

edit 1 sorry for not clearing it up.

mezilord
  • 5
  • 1
  • 6
    what issue are you facing? – Sayse Nov 11 '19 at 11:45
  • 2
    `if len(set(a)) == len(a):` `set` is a function (kinda) that deletes duplications from iterables such as a `list`. And btw: in plain `python` it's not called an `array` but a `list`. – Aryerez Nov 11 '19 at 11:46
  • Since indentation is important, please fix the formatting of your question: https://stackoverflow.com/editing-help – 001 Nov 11 '19 at 11:47

3 Answers3

1

When working with numerical data using numpy's unique might be advantageous over the standard set

import numpy as np
values = [ 1, 2, 3, 4, 5, 6, 20, 40, 2, 4, 5 ]
uniques = np.unique( values )

after this comparison is just the same as using set

if( len( values ) == len( uniques ) ):
    print( "all elements are different" )
else:
    print( "false elements match" )

Naturally, it works best, if the input already is a numpy array.

mikuszefski
  • 3,943
  • 1
  • 25
  • 38
0

Based on what you wrote, A is a list in python..... if its an array please indicate from which library. Array? Numpy? If it is a list, off the top of my head would be:

check = list(set(A))

if len(check) != len(A):
    print("Elements match")
else:
    print("All elements are different")

Shorter version: (thanks nenri)

if len(set(A)) != len(A):
    print("Elements match")
else:
    print("All elements are different")
Jason Chia
  • 1,144
  • 1
  • 5
  • 18
  • 1
    You can directly check the length on the set without having to translate it back to a list. Or, if you make the translation, you can check `check != A` – Nenri Nov 11 '19 at 11:56
  • 1
    Nenri is right. Habit on my part to ensure type remains the same. :P – Jason Chia Nov 11 '19 at 11:59
  • im sorry i have now included the array that i need to use and that is numpy – mezilord Nov 11 '19 at 12:34
0

You can create a set from the elements in the list to remove duplicates from it. Now, to see if there were some duplicates compare the size of your list with the set.

l = [1,2,3,3,4]
s = set(l)
if len(s) < len(l):
    pass