diff options
author | Guido van Rossum <guido@python.org> | 1995-04-10 11:40:26 (GMT) |
---|---|---|
committer | Guido van Rossum <guido@python.org> | 1995-04-10 11:40:26 (GMT) |
commit | 21bc15b73da1e3e5ab60ff9b93a95bfd390fea3f (patch) | |
tree | 6c138d03577d4d75c87e7ddb665dbc535fcf06ad /Demo/comparisons/sortingtest.py | |
parent | f4449def3b0e4d7d2e197920cb7f9db4f2e9df04 (diff) | |
download | cpython-21bc15b73da1e3e5ab60ff9b93a95bfd390fea3f.zip cpython-21bc15b73da1e3e5ab60ff9b93a95bfd390fea3f.tar.gz cpython-21bc15b73da1e3e5ab60ff9b93a95bfd390fea3f.tar.bz2 |
commit -- why not...
Diffstat (limited to 'Demo/comparisons/sortingtest.py')
-rwxr-xr-x | Demo/comparisons/sortingtest.py | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/Demo/comparisons/sortingtest.py b/Demo/comparisons/sortingtest.py new file mode 100755 index 0000000..1de683b --- /dev/null +++ b/Demo/comparisons/sortingtest.py @@ -0,0 +1,50 @@ +#! /usr/local/bin/python + +# 2) Sorting Test +# +# Sort an input file that consists of lines like this +# +# var1=23 other=14 ditto=23 fred=2 +# +# such that each output line is sorted WRT to the number. Order +# of output lines does not change. Resolve collisions using the +# variable name. e.g. +# +# fred=2 other=14 ditto=23 var1=23 +# +# Lines may be up to several kilobytes in length and contain +# zillions of variables. + +# This implementation: +# - Reads stdin, writes stdout +# - Uses any amount of whitespace to separate fields +# - Allows signed numbers +# - Treats illegally formatted fields as field=0 +# - Outputs the sorted fields with exactly one space between them +# - Handles blank input lines correctly + +import regex +import string +import sys + +def main(): + prog = regex.compile('^\(.*\)=\([-+]?[0-9]+\)') + def makekey(item, prog=prog): + if prog.match(item) >= 0: + var, num = prog.group(1, 2) + return string.atoi(num), var + else: + # Bad input -- pretend it's a var with value 0 + return 0, item + while 1: + line = sys.stdin.readline() + if not line: + break + items = string.split(line) + items = map(makekey, items) + items.sort() + for num, var in items: + print "%s=%s" % (var, num), + print + +main() |