Danny Yoo wrote:
> 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!
> 

up to a thousand (not tested)

words = {0:'zero', 1:'one', 2:'two', 3:'three', ... , 10:'ten',
         11:'eleven', 12:'twelve', ..., 19:'nineteen',
         20:'twenty', ...., 90:'ninety', 100:'one hundred' }
def digitToString(n) :
    try :
        retStr = words[n]
    except KeyError :
        if n > 100 :
            retStr = (digitToString(n // 100)
                     + ' hundred and '
                     + digitToString(n % 100))
        else :
            retStr = (digitToString(n - (n % 10))
                     + ' '
                     + digitToString(n % 10))

    return retStr

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

Reply via email to