I have written a code which finds unique elements from the list of integers.
JavaScript
x
21
21
1
def Distinct(arr, n):
2
3
for i in range(0, n):
4
5
d = 0
6
for j in range(0, i):
7
if (arr[i] == arr[j]):
8
d = 1
9
break
10
11
if (d == 0):
12
print(arr[i], end=',')
13
14
15
n = int(input('Enter length of numbers: '))
16
arr = []
17
for i in range(n):
18
a = input('enter the number: ')
19
arr.append(a)
20
print(Distinct(arr, n))
21
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 ?
Advertisement
Answer
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:
JavaScript
1
2
1
Distinct(arr, n)
2
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.
JavaScript
1
5
1
if d == 0 and i == 0:
2
print(arr[i], end='')
3
elif d == 0:
4
print("," + arr[i], end='')
5