-2

I am currently doing an assignment in which I need to read in user input separated by spaces into a list named list1. I then need to iterate over that list and all unique numbers need to be added to a different list name list2.

Finally, I need to print the numbers sorted like 1 2 3 4 5 6 with spaces.

Code

list1 = input('Enter numbers seperated by spaces: ')
list2 = []
    
for num in list1:
    if num not in list2:
        list2.append(num)
    
print(f'The distinct numbers are: {list2}') 

Here is the output that I need to fix.

Write in a string of numbers seperated by a space for each: 3 4 5 6 2
The distinct numbers are: ['3', ' ', '4', '5', '6', '2']
Christopher Peisert
  • 21,862
  • 3
  • 86
  • 117
aroe
  • 499
  • 1
  • 6
  • 15

1 Answers1

1

The first step is to split up the input. Python strings have a built in split() function for just this purpose.

Next, you want to ensure that any empty values are removed. In the example below, the list comprehension checks if each user input item evaluates to True (i.e. not a blank string) and also converts the strings to integers, which is important to sort numerically rather than lexicographically.

The set data type is a container that does not allow duplicates, so you can initialize a new set from the list of numbers to remove duplicates.

The built-in sorted() function can be used to sort the data.

And lastly, the join() function can be used to create a string with each number separated by a space, but in order for this to work, the numbers need to be converted back to strings. Here, the str class creates new strings from each number, which are then passed to join().

Code sample

user_input = input('Enter numbers separated by spaces: ')
string_list = user_input.split()
number_list = [int(x) for x in string_list if x]
unique_numbers = set(number_list)
sorted_list = sorted(unique_numbers)

print(f'You entered distinct values: {" ".join(map(str, sorted_list))}')

Example run

Enter numbers seperated by spaces: 3  4  3 5 32 1 5  4
You entered distinct values: 1 3 4 5 32
Christopher Peisert
  • 21,862
  • 3
  • 86
  • 117