Mercurial > cpython-lru_cache-weakref
annotate Demo/comparisons/sortingtest.py @ 5817:48b94de85bf3 legacy-trunk
Extensive changes by AMK.
| author | Guido van Rossum <guido@python.org> |
|---|---|
| date | Thu, 17 Jul 1997 16:29:42 +0000 |
| parents | 73758db2f464 |
| children | 558689b6d7f0 |
| rev | line source |
|---|---|
|
4573
73758db2f464
/usr/local/bin/python -> /usr/bin/env python
Guido van Rossum <guido@python.org>
parents:
2651
diff
changeset
|
1 #! /usr/bin/env python |
| 2651 | 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 | |
| 26 import regex | |
| 27 import string | |
| 28 import sys | |
| 29 | |
| 30 def main(): | |
| 31 prog = regex.compile('^\(.*\)=\([-+]?[0-9]+\)') | |
| 32 def makekey(item, prog=prog): | |
| 33 if prog.match(item) >= 0: | |
| 34 var, num = prog.group(1, 2) | |
| 35 return string.atoi(num), var | |
| 36 else: | |
| 37 # Bad input -- pretend it's a var with value 0 | |
| 38 return 0, item | |
| 39 while 1: | |
| 40 line = sys.stdin.readline() | |
| 41 if not line: | |
| 42 break | |
| 43 items = string.split(line) | |
| 44 items = map(makekey, items) | |
| 45 items.sort() | |
| 46 for num, var in items: | |
| 47 print "%s=%s" % (var, num), | |
| 48 print | |
| 49 | |
| 50 main() |
