summaryrefslogtreecommitdiff
path: root/sys/src/cmd/python/Demo/comparisons/sortingtest.py
diff options
context:
space:
mode:
authorcinap_lenrek <cinap_lenrek@localhost>2011-05-03 11:25:13 +0000
committercinap_lenrek <cinap_lenrek@localhost>2011-05-03 11:25:13 +0000
commit458120dd40db6b4df55a4e96b650e16798ef06a0 (patch)
tree8f82685be24fef97e715c6f5ca4c68d34d5074ee /sys/src/cmd/python/Demo/comparisons/sortingtest.py
parent3a742c699f6806c1145aea5149bf15de15a0afd7 (diff)
add hg and python
Diffstat (limited to 'sys/src/cmd/python/Demo/comparisons/sortingtest.py')
-rwxr-xr-xsys/src/cmd/python/Demo/comparisons/sortingtest.py51
1 files changed, 51 insertions, 0 deletions
diff --git a/sys/src/cmd/python/Demo/comparisons/sortingtest.py b/sys/src/cmd/python/Demo/comparisons/sortingtest.py
new file mode 100755
index 000000000..cabf6260d
--- /dev/null
+++ b/sys/src/cmd/python/Demo/comparisons/sortingtest.py
@@ -0,0 +1,51 @@
+#! /usr/bin/env python
+
+# 2) Sorting Test
+#
+# Sort an input file that consists of lines like this
+#
+# var1=23 other=14 ditto=23 fred=2
+#
+# 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
+#
+# 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
+import string
+import sys
+
+def main():
+ prog = re.compile('^(.*)=([-+]?[0-9]+)')
+ def makekey(item, prog=prog):
+ match = prog.match(item)
+ if match:
+ var, num = match.group(1, 2)
+ return string.atoi(num), var
+ else:
+ # Bad input -- pretend it's a var with value 0
+ return 0, item
+ while 1:
+ line = sys.stdin.readline()
+ if not line:
+ break
+ items = line.split()
+ items = map(makekey, items)
+ items.sort()
+ for num, var in items:
+ print "%s=%s" % (var, num),
+ print
+
+main()