home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyos2bin.zip / Demo / comparisons / sortingtest.py < prev    next >
Text File  |  1996-11-27  |  1KB  |  51 lines

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