SHARE
TWEET

Untitled

a guest Apr 24th, 2019 73 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Count the length of each of the unique words in a sentence
  2. # and list them in decreasing order
  3.  
  4. input_string = input ( "Enter your string - ")
  5.  
  6. # Split the string into words
  7. words = input_string.split(" ")
  8.  
  9. # Get only the unique words
  10. words = set(words)
  11.  
  12. # Initialize a word length ( as a dictionary)
  13. word_count = {  }
  14.  
  15.  
  16. # # Iterate through the words and start updating the word length counter
  17. for word in words :
  18.  
  19.     # If a word is not already counted, add it to the counter
  20.     if word_count.get(word) == None :
  21.         word_count[word] = len(word)
  22.  
  23. # Dictionaries cannot be sorted. So, create a list of tuples or lists
  24. t_word_count = []
  25. for word in word_count.keys() :
  26.     t_word_count.append( [ word, word_count.get(word) ] )
  27.  
  28. # The sort criteria is the word count
  29. def sort_criteria(ls) :
  30.     return ls[1]
  31.  
  32. # Now sort the list based on the inner list's word length
  33. t_word_count.sort(key = sort_criteria)
  34.  
  35. # Default sorting order is Ascending. If you want descending, set reverse flag to True
  36. # t_word_count.sort(key = sort_criteria, reverse = True)
  37.  
  38.  
  39. # Print them out
  40. for i in t_word_count :
  41.     print (i[0],"----",i[1])
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top