Removing duplicates and sorting list python

Viewed 3654

Given a list, I need to print the numbers in sorted order and remove any duplicates. I am using python 3.7.2

My code:

def sorted_elements(numbers):
    return sorted(set(numbers))

testcase = int(input())
while testcase > 0:
   numbers = input().split()
   l = sorted_elements(numbers)

   for x in l:
      print (x, end = ' ')

   print ()
   testcase -= 1

However, whenever my input consists of a 2 digit number, the logic fails. Eg. for input of 2 1 43 2 5, I get an output of 1 2 43 5.

This work perfectly for single digit numbers. Can someone help me out with this?

5 Answers

You only need a slight modification. You are comparing strings instead of numbers, so try this instead:

def sorted_elements(numbers):
    return sorted(set(numbers))

testcase = int(input())
while testcase > 0:
   numbers = map(int, input().split())
   l = sorted_elements(numbers)

   for x in l:
      print (x, end = ' ')

   print ()
   testcase -= 1

If you want, you can also do:

numbers = (int(x) for x in input().split())

You are going correct way with set(numbers) to remove duplicates. The problem comes from sorted with your numbers being list of strs not ints.

Try this:

x_numbers = input().split()
numbers = [int(x) for x in x_numbers]

You can simplify this in various aspects. Sort by numeric value using an appropriate key function, use a for loop if you know the number of iterations beforehand, utilize appropriate string utils like str.join, etc.

testcases = int(input())

for _ in range(testcases):
    print(' '.join(sorted(set(input().split()), key=int)))

We can keep it simple like this. This is a reference

input=raw_input() #took input as string
inputlist=input.split() #split the string to list
lsintegers = map(int, list(set(inputlist))) #remove duplicates converted each element to integer
lsintegers.sort() #sorted 
print(lsintegers)`
Related