Hi Jason,

Looking back at that Java code:

////////////////////////////////////////////////
    static String convertDigitToEnglish(int d)  {
        switch ( d )
        {
           case 1: return "one";
           case 2: return "two";
           case 3: return "three";
           case 4: return "four";
           case 5: return "five";
           case 6: return "six";
           case 7: return "seven";
           case 8: return "eight";
           case 9: return "nine";
           default: return "\nFatal Error!\n"; // should I abort pgm?
        } // end of switch
   } // end of convertDigitToEnglis
////////////////////////////////////////////////


Frankly, this seems silly to me.  First, it ignores zero, which is a cardinal 
sin.  I'm being somewhat serious about this: functions should do what they say, 
and that function isn't.


But the code could also be written much more tightly as:

////////////////////////////////////////////////
      static String digitToString(int n) {
         String[] words = {"zero", "one", "two", "three", "four",
                          "five", "six", "seven", "eight", "nine"};
         if (0 <= n && n < 10) {
             return words[n];
         }
         throw new IllegalArgumentException("input not a single digit");
     }
////////////////////////////////////////////////

I don't mean to make this post so Java-centric; it just seems a little unfair 
to compare a bad Java routine to a good Python routine.  :) Writing an 
equivalent in Python is also pretty straightforward:

#################################
## Pseudocode: just a sketch
def digitToString(n):
      words = ["zero", "one", ...]
      if 0 <= n < 10:
          return words[n]
     ...
#################################

Like dictionaries, the list data structure works pretty well for key/value 
lookup if the input key is a small number.


Good luck!

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to