SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
0.lists
Exercise:
Programming Excercises
Question:5 | ISBN:978013274719 | Edition: 6

Question

(Print distinct numbers) Write a program that reads in numbers separated by a space in one line and displays distinct numbers (i.e., if a number appears multiple times, it is displayed only once). (Hint: Read all the numbers and store them in list1. Create a new list list2. Add a number in list1 to list2. If the number is already in the list, ignore it.) Here is the sample run of the program:

Enter ten numbers:1 2 3 2 1 6 3 4 5 2
The distinct numbers are: 1 2 3 6 4 5

 

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Print distinct numbers Program code:

# Prompt the user to enter list separated by spaces
num = input("Enter ten numbers: ")

# Convert the input string to a list of list
list = [int(num) for num in num.split()]

# Create a new list to store distinct list
distinctNums = []

# Iterate over the list list
for number in list:
    # Check if the number is already in the distinctNums list
    if number not in distinctNums:
        distinctNums.append(number)

# Display the distinct list
print("The distinct numbers are:", end=" ")
for number in distinctNums:
    print(number, end=" ")

Executed Output:

Enter ten numbers: 1 2 3 2 1 6 3 4 5 2
The distinct numbers are: 1 2 3 6 4 5

 

0 0

Discussions

Post the discussion to improve the above solution.