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:13 | ISBN:978013274719 | Edition: 6

Question

(Eliminate duplicates) Write a function that returns a new list by eliminating the duplicate values in the list. Use the following function header:
                def eliminateDuplicates(lst):
Write a test program that reads in a list of integers, invokes the function, and displays the result.

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

Eliminate duplicates Program code:

# Function to eliminate duplicate values from a list
def eliminateDuplicates(lst):
    # Create an empty list to store distinct values
    distinctNum = []
    
    # Iterate over each element in the input list
    for num in lst:
        # Check if the element is not already in the distinctNum
        if num not in distinctNum:
            # Add the element to the distinctNum
            distinctNum.append(num)
    
    # Return the list with duplicate values eliminated
    return distinctNum

# Test program
def main():
    # Prompt the user to enter ten numbers separated by spaces
    num = input("Enter ten numbers: ")

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

    # Call the eliminateDuplicates function to get the list with duplicate values eliminated
    distinct_numbers = eliminateDuplicates(numbers)

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

# Call the test program
main()

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.