def countchars(s): chars = list(map(chr,range(ord('a'),ord('z')+1))) counts = {} for c in s.lower(): if c not in chars: continue if c not in counts: counts[c] = 1 else: counts[c] += 1 keys = [ (c,counts[c]) for c in counts ] keys.sort(key=lambda c: -c[1]) return keys def maximumbeauty(s): clist = countchars(s) maxbeauty = 0 beauty = 26 for c, count in clist: maxbeauty += count * beauty beauty -= 1 return maxbeauty for s in ["ABbCcc","Good luck in the Facebook Hacker Cup this year!","Ignore punctuation, please :)", "Sometimes test cases are hard to make up.","So I just go consult Professor Dalves"]: print("%s: %d" % (s, maximumbeauty(s)))