cpython/Demo/comparisons/sortingtest.py

46 lines
1.2 KiB
Python
Raw Normal View History

#! /usr/bin/env python
1995-04-10 08:40:26 -03:00
# 2) Sorting Test
#
1995-04-10 08:40:26 -03:00
# Sort an input file that consists of lines like this
#
1995-04-10 08:40:26 -03:00
# var1=23 other=14 ditto=23 fred=2
#
1995-04-10 08:40:26 -03:00
# such that each output line is sorted WRT to the number. Order
# of output lines does not change. Resolve collisions using the
# variable name. e.g.
#
# fred=2 other=14 ditto=23 var1=23
#
1995-04-10 08:40:26 -03:00
# Lines may be up to several kilobytes in length and contain
# zillions of variables.
# This implementation:
# - Reads stdin, writes stdout
# - Uses any amount of whitespace to separate fields
# - Allows signed numbers
# - Treats illegally formatted fields as field=0
# - Outputs the sorted fields with exactly one space between them
# - Handles blank input lines correctly
import re
1995-04-10 08:40:26 -03:00
import sys
def main():
prog = re.compile('^(.*)=([-+]?[0-9]+)')
def makekey(item, prog=prog):
match = prog.match(item)
if match:
2009-10-25 17:25:43 -03:00
var, num = match.groups()
return int(num), var
else:
# Bad input -- pretend it's a var with value 0
return 0, item
2009-10-25 17:25:43 -03:00
for line in sys.stdin:
items = sorted(makekey(item) for item in line.split())
for num, var in items:
print "%s=%s" % (var, num),
print
1995-04-10 08:40:26 -03:00
main()