Upload
paul-thomas
View
213
Download
1
Embed Size (px)
Citation preview
What we want to achieve Convert a single integer number between 0 and
999 into its word form as in: Enter an integer number between 0 and 999: 537
Five hundred thirty-seven Enter an integer number between 0 and 999: 50
Fifty Enter an integer number between 0 and 999: 0
Zero
Clarifications
Your program will have to convert a single numberNo loops
The number will always be an integerNo decimal part (except for extra credit)
The text form of the number shouldHave its first letter capitalized
There is a string function for thatSpell out 57 as fifty-seven
The way to proceed
We will divide the task into subtasks in order to conquer itHandling the hundredsHandling the tens, twenty and aboveHandling numbers between 0 and 19
Python 3 integer division and remainder operators In Python 3, but not in Python 2,
>>> 3/2
1.5
>>> 3//2
1
>>> 3%2
1
Regular division: /
Integer division: //
Reminder: %
Using these operators
Assume number is 547hundreds = number//100 is equal to 5nohundreds = number%100 is equal to 47tens = nohundreds//10 is equal to 4notens = nohundreds//10 is equal to 7
Using lists
Algorithm uses two lists:value = ['zero', 'one', ..., 'nineteen'] with
value[1] = 'one' ... value[19] = 'nineteen'
value10 = ['zero', 'ten', ..., 'ninety'] with value10[2] = 'twenty' ... value10[19] = 'ninety'
Overall organization (I)
Read the number and convert it to an int Set up two conversion lists Initialize result to "" (empty string) if number > 99 :
hundreds = number // 100Add to result value[hundreds] + " hundred "
Overall organization (II)
nohundreds = number % 100Does nothing if number < 100
if nohundreds > 19 : tens = nohundreds//10Add to result tenvalue[tens] + "-"remainder = nohundreds%10
else :remainder = nohundreds%19
Overall organization (III)
if remainder > 0 :Add to result value[remainder]
if number == 0 : result = zero
Cleanup:Capitalize first letter of resultRemove any trailing '-' from result
Print out result
Comments
Main issue was to avoid outputs like
Zero hundred twenty-two
Two hundred zero five
Two hundred zero
Fifty zero
Ten-five
not to mention
Five hundred Fifty-Three
Extra credit
You will get ten extra points out of one hundred if your program handles real numbers:
Enter a number between 0 and 999: 537Five hundred thirty-seven even
Enter an number between 0 and 999: 537.25Five hundred thirty-seven and 25/100
Enter a number between 0 and 999: 0.25Zero and 25/100
That's what I would write on a check!