Page 404 - Computer Science V2.0 Class 11
P. 404

Solved Programming Questions
              1.   Write a function to remove the duplicate elements from a list. You are not allowed to create a new list within the
                  function. Make use of it to write a program that accepts as input a list from a user and display the list without
                  duplicates.

                01 def removeDuplicates(lst):
                02     '''
                03     Objective: To remove duplicates from the input list
                04     Input Parameter:
                05        lst- a list, possibly with duplicate elements
                06     Return Value: None
                07     Side Effect: The modified list has the duplicates removed
                08     '''
                09     #Approach: For each element, remove it if its count>0.
                10
                11     for element in lst:
                12         while lst.count(element)>1:
                13             lst.remove(element)
                14     return lst
                15 lst = eval (input('Enter the list:\n'))
                16 lst = removeDuplicates(lst)
                17 print("After removing duplicate elements", lst)

              Sample output:
               >>> Enter the list:
                    [4, 6, 2, 5, 6, 3, 6, 4, 9, 2, 4, 6, 7, 4, 6, 7]
               >>> After removing duplicate elements [5, 3, 9, 2, 4, 6, 7]

              2.   Write a function to create a list that is devoid of duplicates in the given list. Make use of it to write a program that
                  accepts as input a  list from a user and display the list without duplicates.
                01 def removeDuplicates(lst1):
                02     '''
                03     Objective: To return list without duplicates.
                04     Input Parameter: lst1- list with duplicate elements
                05     Return Value: A list without duplicate elements
                06     '''
                07     lst2 = []
                08     for element in lst1:
                09         if element not in lst2:
                10             #append  it to lst2
                11             lst2.append(element)
                12     return lst2
                13
                14 # Objective: To remove duplicate from a list
                15 myList = eval(input('Enter the list:\n'))
                16 result = removeDuplicates(myList)
                17 print('List with no duplicates:' , result)
                18 print('Original List:' , myList)

              Sample output:
               >>> Enter the list:
                    [4, 6, 2, 5, 6, 3, 6, 4, 9, 2, 4, 6, 7, 4, 6, 7]
                    List with no duplicates: [4, 6, 2, 5, 3, 9, 7]
                    Original List: [4, 6, 2, 5, 6, 3, 6, 4, 9, 2, 4, 6, 7, 4, 6, 7]


               390   Touchpad Computer Science (Ver. 2.0)-XI
   399   400   401   402   403   404   405   406   407   408   409