Advertisement
gauravssnl

remove_duplicates_and_sort.py

Feb 25th, 2017
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.34 KB | None | 0 0
  1. # remove_duplicates.py by gauravssnl
  2.  
  3. # this script removes duplicate characters from string and sort characters and count number of duplicates.For example : remove_duplicates( "aaabbbac") = ( "abc" , 5)
  4.  
  5. def remove_duplicates( InputStr ) :
  6.    
  7.     # stores duplicates count in dictionary repDict where character will be key and its repitition count will be value
  8.     repDict = { }
  9.    
  10.     for ch in InputStr :
  11.        
  12.         # when character ch has been already read & stored in dictionary and is being repeated ,we increase its repititon count by 1
  13.         if repDict.has_key( ch ) :
  14.             repDict[ ch ] +=1
  15.        
  16.         # when character ch is read for first time , we set its repetition count to 0
  17.         else :    
  18.             repDict[ch] = 0
  19.        
  20.     # print(repDict)
  21.     # use repDict to return sorted string and total number of duplicate characters
  22.     rep_count = sum( repDict.values( ) )
  23.    
  24.     result_keys = repDict.keys( )
  25.     # sort result_key to sort characters
  26.     result_keys.sort()
  27.    
  28.     result = ''
  29.     for key in result_keys :
  30.         result += key
  31.     # print(rep_count)
  32.     # print(result)
  33.    
  34.     return ( result , rep_count)
  35.        
  36. if __name__ == "__main__" :
  37.    
  38.     print (remove_duplicates( 'aaabbbac' ) )
  39.    
  40.     print (remove_duplicates( 'ccbbaabaabbcef' ) )
  41.     print( remove_duplicates( '' ))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement