2014-02-11 HW

posted Mar 11, 2014, 4:56 AM by Samuel Konstantinovich   [ updated Mar 11, 2014, 6:11 AM ]

PopQuiz: 10 minutes

1. Write a function integerToWords(x) that accepts an integer x, in the range 1 to 5 and returns the same number spelled out as a word.


integertowords(5) returns “five”        integertowords(3) retrns “three”

2.Given the definitions of foo and bar below:

 def foo(a):

  if a==0:

    return True


    return bar(a-1)

 def bar(a):

  if a==0:

    return False


    return foo(a-1)

Evaluate the function calls:

2a. foo(4)                        2b. bar(6)

 3. What is the output of the following code:


while g<100:

  print g


 4. What is the output of the following code:


while g<19:

  if g%5==0:



  print g

Classwork Notes: 

You are writing a function that converts numbers to the string that represents the English word for the numbers.

Part 1:

numToWords9(i)  that accepts any integers from 1 to 9 inclusive. The result should be the word that corresponds to the digit.

    numToWords9(3) returns "three"

    numToWords9(9) returns "nine"

We want to use this to write a more robust num to words function that works from 1-99 inclusive, we will call this numToWords99(i).  Notice the last digit of the function name tells you the maximum value you can give it. 

Part 2:


This function has 3 cases:

  • Trivial: when i < 10. This means we can use the original numToWords9 function to get the result!
  • Easy: when i is 10 through 19 [10-19 do not follow normal rules like 34 44 54 14]

      This means we need to write code to produce these which will be similar to how we wrote the first function.

  • Moderate: when i is from 20-99. This requires us to break apart the number into two parts the tens place and the ones place. Then assemble a string using two parts (examples to follow) 
Example:  34
    The tens place is 3, so you say "thirty", the ones place is 4, so you say "four", join them together with a space in between.
Example:  50
    The tens place is 5, so you say "fifty", the ones place is 0, so you don't add anything else to the number.

Part 3: (You can stop at 999)

THINK! We can use numToWords9 to help us define numToWords99. Now that you have working words for 1-99, you can define a function that works with 1-999 (use numToWords99 to handle the tens/ones place.)


  Try to write numToWords999  as a recursive function. 

Part 4:

I will give you a wrapper function to handle zero and negative numbers: 

def numToString(x):

    if x<0:

        return "negative "+numToString(abs(x))

        #this handles negative numbers 

    if x==0:

        return "zero"

        #this is the only time you ever say the word Zero


        return intToString9____(x) 

        #place the intToString9___ function that works with the largest number here. 

        #you should have intToString99 working by the end of Friday.