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