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