I wondered if I could do better performance-wise, based on knowledge of the problem that the more general built-in classes couldn't take advantage of. Ended up with this:
import string
longString="..."
def decode(msg):
# Testing suggests this is a little faster than using defaultdict
charCountHash = {}.fromkeys(string.ascii_lowercase,0)
charCountHash['_'] = 0
for ch in msg:
charCountHash[ch] += 1
c = charCountHash['_']
resultHash = {charCountHash[k]: k for k in charCountHash.keys() \
if charCountHash[k] > c }
return ''.join( [ resultHash[index] for index in \
sorted(resultHash.keys(), reverse=True) ] )
print(decode(longString))
Testing both implementations a few times suggests this way is faster, but only 1% or so.
Ryan is an engineer in the Sacramento Area with a focus in Python, Ruby, and Rust. Bash/Python Exercism mentor. Coding, physics, calculus, music, woodworking. Looking for work!
Nice! I haven't used fromkeys before. That's a nice alternative to defaultdict (and you don't have to import anything!) if you already know the keys you need.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I wondered if I could do better performance-wise, based on knowledge of the problem that the more general built-in classes couldn't take advantage of. Ended up with this:
Testing both implementations a few times suggests this way is faster, but only 1% or so.
Might try this in go, just for the practice...
Nice! I haven't used
fromkeys
before. That's a nice alternative to defaultdict (and you don't have to import anything!) if you already know the keys you need.