Sorting a string to make a new one
<p>Here I had to remove the most frequent alphabet of a string(if frequency of two alphabets is same, then in alphabetical order) and put it into new string.</p>

<p>Input:</p>

<pre><code>abbcccdddd
</code></pre>

<p>Output:</p>

<pre><code>dcdbcdabcd
</code></pre>

<p>The code I wrote is:</p>

<pre><code>s = list(sorted(&lt;the input string&gt;))
a = []
for c in range(len(s)):
    freq =[0 for _ in range(26)]
    for x in s:
        freq[ord(x)-ord('a')] += 1
    m = max(freq)
    allindices = [p for p,q in enumerate(freq) if q == m]
    r = chr(97+allindices[0])
    a.append(r)
    s.remove(r)
print''.join(a)
</code></pre>

<p>But it passed the allowed runtime limit maybe due to too many loops.(There's another for loop which seperates the strings from user input)</p>

<p>I was hoping if someone could suggest a more optimised version of it using less memory space. </p>

<p>Since the alphabet will always be a constant 26 characters,
this will work in O(N) and only takes a constant amount of space of 26</p>

<pre><code>from collections import Counter
from string import ascii_lowercase

def sorted_alphabet(text):
    freq = Counter(text)
    alphabet = filter(freq.get, ascii_lowercase) # alphabet filtered with freq &gt;= 1
    top_freq = max(freq.values()) if text else 0 # handle empty text eg. ''
    for top_freq in range(top_freq, 0, -1): # from top_freq to 1
        for letter in alphabet:
            if freq[letter] &gt;= top_freq:
                yield letter

print ''.join(sorted_alphabet('abbcccdddd'))
print ''.join(sorted_alphabet('dbdd'))
print ''.join(sorted_alphabet(''))
print ''.join(sorted_alphabet('xxxxaaax'))
</code></pre>

<hr>

<pre><code>dcdbcdabcd
ddbd

xxaxaxax
</code></pre>

python string python-2.7 sorting nested-loops