Lecture 23 + HW

posted Mar 7, 2013, 6:18 AM by Samuel Konstantinovich   [ updated Mar 18, 2014, 5:33 AM ]


1. If you were absent, it is critical that you read yesterday's notes and work on those problems, you must do this at home since you have other work to do now:

Do now:

2.This is something you should be familiar with (You can work in pairs if you aren't sure) On paper how can you add up the digits of an integer, write this function two ways:

2a. Do this using recursion

2b. Do this using a loop

examples: (both 2a and 2b should give the same results:)

sumDigits(134) returns 8

sumDigits(591) returns 15

ANSWER to sumDigits:

#both version 2's stop 1 step earlier, and need to add the x value to the answer at the end (or return the x value)

#Recursive version 1

def sumDigits(x):

    if x>0:

        return sumDigits(x/10) + x%10


        return 0

#Recursive version 2

def sumDigits(x):

    if x>9:

        return sumDigits(x/10) + x%10


        return x


#Using a while loop version 1:       

def sumDigits(x):


    while x>0:



    return total

#Using a while loop version 2:       

def sumDigits(x):


    while x>9:



    return total + x

At this point everyone should log in with the partners from yesterday to work on the following two problems:

3. Bondify

Write a function Bondify(name) takes a string as a parameter in the format "first last" it then rearranges the name in the James bond convention shown below:

bondify("James Kim") returns 'Kim, James Kim'

bondify("Xiao-Xiao Zhou") returns 'Zhou, Xiao-Xiao Zhou'

bondify("Vlademir Gorodetski") returns 'Gorodetski, Vlademir Gorodetski'

4. Pig Latin!


if a word starts with a vowel then add “ay” to the word


egg becomes eggay

art becomes artay

if a word starts with a consonant then move the consonant to the end of the word, and then ad ay:


duck becomes uckday

mom becomes ommay

somalia becomes omaliasay

a. Make a pig latin translator that takes one word and applies the pig latin rules to it.


b. Improve your translator to include 'th' and 'ch' and other combinations of letters (digraphs)


the becomes ethey (uh-they)

cheese becomes eesechay

should becomes ouldshay

Homework - String methods

1. Find documentation on 'string methods', this is the name of the commands that work on strings that are built in to python. Your job is to research how to use them.

Here are a few of them to help you find the list of methods:




2. Figure out how to use string methods. Pick 5 of them that would be very useful to know (methods that are opposites such as : upper/lower count as one). Test a few examples of how to use each of the 5. This is a good time to actually print the contents of the python shell. (You can copy/paste it into a word processor to format it better.) Bring a paper copy to school tomorrow.

Here is a place you can look: (ignore string formatting)