Home > Enterprise >  Finding unique elements from the list of given numbers
Finding unique elements from the list of given numbers

Time:12-08

I have written a code which finds unique elements from the list of integers.

def Distinct(arr, n):

    for i in range(0, n):

        d = 0
        for j in range(0, i):
            if (arr[i] == arr[j]):
                d = 1
                break

        if (d == 0):
            print(arr[i], end=',')
    

n = int(input('Enter length of numbers: '))
arr = []
for i in range(n):
    a = input('enter the number: ')
    arr.append(a)
print(Distinct(arr, n)) 

if my given input array is [1,2,2,3,4] where n = 5 i get the output as 1,2,3,4,None but i want the output to be 1,2,3,4 can anyone tell how to fix this ?

CodePudding user response:

Your function Distinct has no return statement so it will always return None. When you call print(Distinct(arr, n)) this is printing the None that is returned. You can simply remove the print() like so:

Distinct(arr, n)

To remove the last comma you can't print a comma on the first iteration, then print the commas before the items. This is because you don't know which item will be the last one.

if d == 0 and i == 0:
    print(arr[i], end='')
elif d == 0:
    print(","   arr[i], end='')

CodePudding user response:

Try something like this:

def Distinct(arr, n):
    lst = []
    for i in range(0, n):
        for j in range(0, i):
            if (arr[i] == arr[j]):
                lst.append(arr[i])
                break
    print(*lst, sep=',')
    

n = int(input('Enter length of numbers: '))
arr = []
for i in range(n):
    a = input('enter the number: ')
    arr.append(a)
Distinct(arr, n)

So first you compute all the numbers, and only at the end you print them

  • Related