Page 354 - Computer Science Class 11 With Functions
P. 354

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]
        3.   Given a list (say, list1) of numbers, its cumulative list is another list (say, list2) whose ith element is the sum of all
            elements till the ith element of lst1. If a list is empty then its cumulative list will also be  an empty list. Write a
            program that accepts a list of integers and displays its cumulative list.
          01 def cumulativeList(lst1):
          02     '''
          03      Objective: To return another list whose ith element is the sum of all elements
          04     till ith element of lst1
          05     Input Parameter: lst1- list
          06     Return value: cumLst - list

         352   Touchpad Computer Science-XI
   349   350   351   352   353   354   355   356   357   358   359