Skip to content

Instantly share code, notes, and snippets.

@trehn
Created June 26, 2014 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trehn/e1dd8ed2e1a72e453c41 to your computer and use it in GitHub Desktop.
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
#!/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