PageRenderTime 62ms CodeModel.GetById 40ms app.highlight 3ms RepoModel.GetById 17ms app.codeStats 0ms

/Demo/comparisons/sortingtest.py

http://unladen-swallow.googlecode.com/
Python | 51 lines | 23 code | 5 blank | 23 comment | 6 complexity | fc4bca9c3e4999d8df7dbd21d99c402f MD5 | raw file
 1#! /usr/bin/env python
 2
 3# 2)  Sorting Test
 4#
 5#     Sort an input file that consists of lines like this
 6#
 7#         var1=23 other=14 ditto=23 fred=2
 8#
 9#     such that each output line is sorted WRT to the number.  Order
10#     of output lines does not change.  Resolve collisions using the
11#     variable name.   e.g.
12#
13#         fred=2 other=14 ditto=23 var1=23
14#
15#     Lines may be up to several kilobytes in length and contain
16#     zillions of variables.
17
18# This implementation:
19# - Reads stdin, writes stdout
20# - Uses any amount of whitespace to separate fields
21# - Allows signed numbers
22# - Treats illegally formatted fields as field=0
23# - Outputs the sorted fields with exactly one space between them
24# - Handles blank input lines correctly
25
26import re
27import string
28import sys
29
30def main():
31    prog = re.compile('^(.*)=([-+]?[0-9]+)')
32    def makekey(item, prog=prog):
33        match = prog.match(item)
34        if match:
35            var, num = match.group(1, 2)
36            return string.atoi(num), var
37        else:
38            # Bad input -- pretend it's a var with value 0
39            return 0, item
40    while 1:
41        line = sys.stdin.readline()
42        if not line:
43            break
44        items = line.split()
45        items = map(makekey, items)
46        items.sort()
47        for num, var in items:
48            print "%s=%s" % (var, num),
49        print
50
51main()