title: Best approach to this question using python
body: <p>I am new to python and practicing some problems. Unable to optimize my solution for below problem.</p>
  <p>problem statement: Encode words in sentence based on word frequency and return their <strong>rank</strong> and encoded value for the word.</p>
  <p>example:
  input string --&gt; 'aaa bb ccc aaa bbb bb cc ccc ccc bb ccc bbb'</p>
  <p>expected output --&gt; 3|2|1|3|4|2|5|1|1|2|1|4</p>
  <p>Explanation:- because 'aaa' came 2 times in the original string, and 'ccc' 4 times and 'bb' 3 times, hence they get ranking based on frequency. In that manner 'ccc' rank is 1, 'bb' rank is 2, 'ccc' rank is 3. Hence the result as mentioned above.</p>
  <p>Below is my python code, but unable to optimize it. Can someone please help.</p>
  <pre><code>def testing(s):
      ht = {}
      new_strs = strs.split()
      print(new_strs)
      for i in new_strs:
          if i in ht:
              ht[i] += 1
          else:
              ht[i] = 1
      print(ht)
      
      temp = list(map(list, sorted(ht.items(), key=lambda v: v[1], reverse=True)))
      print(temp)
  
      for k,v in enumerate(temp):
          temp[k].append(k+1)
      print(temp)
      
      final = []
      for j in new_strs:
          for t in temp:
              if t[0] == j:
                  final.append(str(t[2]))
      return '|'.join(final)
  
  strs = 'aaa bb ccc aaa bbb bb cc ccc ccc bb ccc bbb'
  result = testing(str)
  print(result)
  
  </code></pre>
  <p>Below is the result i am getting from this code.</p>
  <pre><code>['aaa', 'bb', 'ccc', 'aaa', 'bbb', 'bb', 'cc', 'ccc', 'ccc', 'bb', 'ccc', 'bbb']
  
  {'aaa': 2, 'bb': 3, 'ccc': 4, 'bbb': 2, 'cc': 1}
  
  [['ccc', 4], ['bb', 3], ['aaa', 2], ['bbb', 2], ['cc', 1]]
  
  [['ccc', 4, 1], ['bb', 3, 2], ['aaa', 2, 3], ['bbb', 2, 4], ['cc', 1, 5]]
  
  3|2|1|3|4|2|5|1|1|2|1|4
  </code></pre>
  <p>Thank you in advance for your help.</p>