1. brickZA
  2. homework

Commits

brickZA  committed 64d31ef

Fixed sorted.py, added unittests

  • Participants
  • Parent commits dbbb8d0
  • Branches default

Comments (0)

Files changed (5)

File .hgignore

View file
  • Ignore whitespace
+syntax:glob
+*.pyc
+*~
+*.ropeproject
+*.ropeproject/*

File sorter/sorted.txt

View file
  • Ignore whitespace
+0
+1
+1
+3
+3
+3
+4
+5
+6
+12
+21
+100
+300

File sorter/sorter.py

View file
  • Ignore whitespace
+#!/usr/bin/env python
+
+"""A simple program for sorting a file of numbers using numerical rather than lexical ordering.
+
+   Run using: python sorter.py unsorted.txt sorted.txt
+   """
+
+import sys
+
+
+def read(fname):
+    f = open(fname)
+    a = f.read().splitlines()
+    return a
+
+
+def write(fname, a):
+    f = open(fname, 'w')
+    f.write('\n'.join(a))
+    f.write('\n')                       # add Trailing new line
+    f.close()
+
+def main(infile, outfile):
+    a = read(infile)
+    def keyfn(item):
+        done = False
+        try:
+            val = int(item)
+            done = True
+        except ValueError:
+            pass
+        try:
+            val = float(item)
+        except ValueError:
+            pass
+        if not done:
+            val = item
+        return val
+    
+    a.sort(key=keyfn)
+    write(outfile, a)
+
+
+if __name__ == "__main__":
+    infile, outfile = sys.argv[1:]
+    main(infile, outfile)

File sorter/test_sorter.py

View file
  • Ignore whitespace
+import unittest
+import tempfile
+import os
+import sorter
+
+class test_Sorter(unittest.TestCase):
+    def setUp(self):
+        self.input_test_string = "1\n10\n3"
+        self.output_test_string = "1\n3\n10\n"
+
+    def test_write(self):
+        temp_file = tempfile.NamedTemporaryFile(delete=False)
+        temp_file.file.close()
+        try:
+            sorter.write(temp_file.name, self.output_test_string.split())
+            actual = open(temp_file.name).read()
+        finally:
+            temp_file.unlink(temp_file.name)
+
+        self.assertEqual(actual, self.output_test_string)
+            
+    def test_read(self):
+        temp_file = tempfile.NamedTemporaryFile(delete=False)
+        temp_file.file.write(self.input_test_string)
+        temp_file.file.close()
+        try:
+            actual = sorter.read(temp_file.name)
+        finally:
+            temp_file.unlink(temp_file.name)
+        self.assertEqual(actual, self.input_test_string.split())
+
+    def test_main(self):
+        sorter.main('unsorted.txt', 'test_sorted.txt')
+        actual = open('test_sorted.txt').read()
+        desired = open('sorted.txt').read()
+        self.assertEqual(actual, desired)
+
+if __name__ == "__main__":
+    unittest.main()

File sorter/unsorted.txt

View file
  • Ignore whitespace
+1
+3
+4
+5
+6
+3
+1
+300
+3
+0
+12
+21
+100