sortingtest.py 1.25 KB
Newer Older
1
#! /usr/bin/env python3
Guido van Rossum's avatar
Guido van Rossum committed
2 3

# 2)  Sorting Test
4
#
Guido van Rossum's avatar
Guido van Rossum committed
5
#     Sort an input file that consists of lines like this
6
#
Guido van Rossum's avatar
Guido van Rossum committed
7
#         var1=23 other=14 ditto=23 fred=2
8
#
Guido van Rossum's avatar
Guido van Rossum committed
9 10 11
#     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.
12 13 14
#
#         fred=2 other=14 ditto=23 var1=23
#
Guido van Rossum's avatar
Guido van Rossum committed
15 16 17 18 19 20 21 22 23 24 25
#     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

26
import re
Guido van Rossum's avatar
Guido van Rossum committed
27 28 29
import sys

def main():
30
    prog = re.compile('^(.*)=([-+]?[0-9]+)')
31
    def makekey(item, prog=prog):
32 33
        match = prog.match(item)
        if match:
Georg Brandl's avatar
Georg Brandl committed
34 35
            var, num = match.groups()
            return int(num), var
36 37 38
        else:
            # Bad input -- pretend it's a var with value 0
            return 0, item
Georg Brandl's avatar
Georg Brandl committed
39 40
    for line in sys.stdin:
        items = sorted(makekey(item) for item in line.split())
41
        for num, var in items:
42 43
            print("%s=%s" % (var, num), end=' ')
        print()
Guido van Rossum's avatar
Guido van Rossum committed
44 45

main()