-
-
Save tomhennigan/32e0d6ec4e25311bfd11 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How bout this:
also, did you see: https://gist.github.com/ssadler/6842183