Skip to content

Instantly share code, notes, and snippets.

@tomhennigan
Last active December 24, 2015 17:59
Show Gist options
  • Save tomhennigan/32e0d6ec4e25311bfd11 to your computer and use it in GitHub Desktop.
Save tomhennigan/32e0d6ec4e25311bfd11 to your computer and use it in GitHub Desktop.
"""
Test:
Given two strings, `a` and `b`. Sort the letters in `a` by the order of letters in `b`.
For example:
a = "ssttexeste"
b = "test"
result = "ttteeesssx"
"""
from collections import defaultdict
def a_by_b(a, b):
# Build a dict f of letter frequencies in a.
f = defaultdict(int)
for c in a:
f[c] += 1
# Run through the chars in b.
r = ''
for c in b:
if c in f:
r += (c * f[c])
f[c] = 0
# Any leftovers.
for c, n in f.iteritems():
if n > 0:
r += (c * f[c])
return r
def test():
a = "adlkfhxaxjxkxhxfwkhkjfhjkahjksedeheflhadslfkhdfjkadhjhdhskghdjdjkhskkhjokhkshakhlhfkjdshjfkshhkskskss"
b = "alskdjfhg"
r = a_by_b(a, b)
s = r[:len("aaaaaallllssssssssssskkkkkkkkkkkkkkkkkkkkdddddddddjjjjjjjjjjjffffffffhhhhhhhhhhhhhhhhhhhhhg")]
e = r[len("aaaaaallllssssssssssskkkkkkkkkkkkkkkkkkkkdddddddddjjjjjjjjjjjffffffffhhhhhhhhhhhhhhhhhhhhhg"):]
assert r.startswith(s) # Check the sorted start.
assert sorted(e) == ['e'] * 3 + ['o'] + ['w'] + ['x'] * 5 # Check the remaining chars aren't dropped.
if __name__ == '__main__':
test()
@ssadler
Copy link

ssadler commented Oct 5, 2013

How bout this:

sorted("ccbbaae", key="abc".find)

also, did you see: https://gist.github.com/ssadler/6842183

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment