One of the AlgorithmQuiz

See CountingCodeLines

   1 import unittest
   2 from cStringIO import StringIO
   3 
   4 def countLines(aFile):
   5     nlines = 0
   6     inComment = False
   7     for line in aFile:
   8         line = line.strip()
   9         if line.startswith('//'):
  10             continue
  11         if line.startswith('/*'):
  12             inComment = False
  13         if line.find('*/') >= 0:
  14             inComment = True
  15         if line and not inComment:
  16             nlines+=1
  17     return nlines
  18 
  19 class Test(unittest.TestCase):
  20     def test1(self):
  21         input = StringIO("""\
  22 // This file contains 3 lines of code
  23 public interface Dave {
  24   /**
  25    * count the number of lines in a file
  26    */
  27    int countLines(File inFile); // not the real signature!
  28 }""")
  29         self.assertEquals(3, countLines(input))
  30 
  31     def test2(self):
  32         input = StringIO("""\
  33 /*****
  34 * This is a test program with 5 lines of code
  35 *  \/* no nesting allowed!
  36 //*****//***/// Slightly pathological comment ending...
  37 
  38 public class Hello {
  39     public static final void main(String [] args) { // gotta love Java
  40       // Say hello
  41       System./*wait*/out./*for*/println/*it*/("Hello/*");
  42    }
  43 
  44 }""")
  45         self.assertEquals(5, countLines(input))
  46 
  47 if __name__=='__main__':
  48     unittest.main()

CountingCodeLines (last edited 2011-08-03 11:00:50 by localhost)

web biohackers.net