Pig Latin - a beginner lesson with some depth
I recently did a unit where I had my students convert words into Pig Latin. I like the problem because to start it only requires strings, functions and if statements but there is some depth to the unit.
We start with simplified rules:
- If the word starts with a vowel, add "ay" to the end of the word
- If it starts with a consonant move the first latter to the end and add "ay"
- don't worry about anything else
Students usually start with something like this:
as students realize it's much easier to check for vowels rather than consonants.
Some students discover that you can do any of the following instead of the big compound or :
This allows us to talk a little about lists (and tuples if you like) as well as now strings are similar to them in certain ways.
By itself, this is a nice little beginner project but it gets better.
Since we talked a bit about lists and strings in the refinement, we
then talk about using python's split()
method that parses a string
on whitespace. We also talk about the for
loop. Ultimately this
leads us to writing a function to convert a sentence into Pig Latin:
But this doesn't work with real sentences. Let's focus on two problems. The first is that it won't handle the period at the end of the sentence properly. It would take that last word, let's say dog. and convert it to og,day rather than ogday.. It also doesn't handle capital letters. There are other issues but they have similar solutions to the ones we'll use for these two.
This is where things get fun.
To handle the period, students frequently jump to modifying the if
conditions in piglatinify
:
or something similar.
This is a straighforward working solution but it's also a great place to introduce the idea of changing the data instead of using complex conditionals to handle special cases (earlier posts here and here).
If we take out the period we can do our regular piglatinify and then add it back in. This leads us to a solution like this:
We can do something similar to deal with words that start with upper case letters:
You can approach other special cases similarly.
So, there you have it. A fun little problem that you can do with your students early on in a CS0 with surprising depth.