Created
June 26, 2014 15:38
-
-
Save trehn/e1dd8ed2e1a72e453c41 to your computer and use it in GitHub Desktop.
This is basically another implementation of the "Alphanum Algorithm" from http://www.davekoelle.com/alphanum.html
This file contains hidden or 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
#!/usr/bin/env python3 | |
# | |
# This is basically another implementation of the "Alphanum Algorithm" | |
# from http://www.davekoelle.com/alphanum.html | |
# | |
# It accepts lines of strings on stdin and prints the sorted result to | |
# stdout. | |
# | |
import fileinput | |
from functools import cmp_to_key | |
UNICODE_MAX = 1114111 # highest Unicode code point | |
def num_values(line): | |
""" | |
Turns a line of text into a list of integers, converting characters | |
to their ordinal value while keeping integers intact as a single | |
element. | |
Integers are added to the highest code point index in Unicode to | |
ensure that they end up after any letter in the sort order. | |
>>> num_values("a47b") | |
[97, 1114158, 98] | |
""" | |
numlist = [] | |
current_int_value = 0 | |
for character in line: | |
if character.isdigit(): | |
current_int_value = current_int_value * 10 | |
current_int_value += int(character) | |
continue | |
if current_int_value > 0: | |
numlist.append(current_int_value + UNICODE_MAX) | |
current_int_value = 0 | |
numlist.append(ord(character)) | |
if current_int_value > 0: | |
numlist.append(current_int_value + UNICODE_MAX) | |
return numlist | |
if __name__ == '__main__': | |
l = list(fileinput.input()) | |
l.sort(key=cmp_to_key(lambda a, b: 1 if num_values(a) > num_values(b) else -1)) | |
for line in l: | |
print(line, end="") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment