how to find out if elements of array are unique? python.?

so far i have this code written:

import random

def unique(array):

    i = 0

    for i in range(len(array)):

        # if array[0] == array[0], array[1], array[2], array[3], array[4]:

            print("The elements in the list are not unqiue.")

            return False

def main():

    n = 5

    x = random.randint(0,10)

    array = []

    for x in range(n):

        array.append(random.randint(0,10))

    print(f"The original list is: {array}")

    output = unique(array)

    print()

if __name__ == "__main__":

    main ()

# ------ #

ik that my main function is already good.... does anyone have any idea on how i could do the unique function

2 Answers

Relevance
  • 3 months ago
    Favorite Answer

    If you want to do it like you're writing a program in C or Java, use nested for loops

    def is_unique(data):

        for i in range(len(data)):

            for j in range(i+1, len(data)):

                if data[i] == data[j]:

                    return False

        return True

    The outer loop on i goes from 0 to n-1, where n is the length of the data argument.

    The inner loop on j goes from i+1 to n-1.  So when i=0, the "if data[i] == data[j]" test will compare data[0] against data[1], data[2], .... data[n-1]. When i is 1, that compares data[1] to data[2], data[3], ... data[n-1]; and so on.

    Python has some features that languages like C and Java do not. You can test for uniqueness in a single expression:

        len(data) == len(set(data))

    ...since set(data) constructs a set object using the elements from data, and a set only contains unique elements.  If building a set produces the same number of elements, then no duplicates were discarded.  All of the elements in data were unique.

    That shorter version will typically run faster, but use more memory than the nested loop version.

  • Anonymous
    3 months ago

    Sort the array.

    Look for a number being the same as the next one.

Still have questions? Get your answers by asking now.