13 Twelve Days of Christmas: Algorithm design

 

Perhaps one of the worst songs of all time, and the one that is sure to ruin my Christmas spirit, is “The Twelve Days of Christmas.” WILL IT EVER STOP!? AND WHAT IS WITH ALL THE BIRDS?! Still, it’s pretty interesting to write an algorithm to generate the song starting from any given day because you have to count up as you add each verse (day) and then count down inside the verses (recapitulating the previous days’ gifts). You’ll be able to build on what you learned writing the program for “99 Bottles of Beer.”


Our program in this chapter will be called twelve_days.py, and it will generate the “Twelve Days of Christmas” song up to a given day, specified by the -n or --num argument (default 12). Note that there should be two newlines between verses but only one at the end:

$ ./twelve_days.py -n 3
On the first day of Christmas,
My true love gave to me,
A partridge in a pear tree.
 
On the second day of Christmas,
My true love gave to me,
Two turtle doves,
And a partridge in a pear tree.
 
On the third day of Christmas,
My true love gave to me,
Three French hens,
Two turtle doves,
And a partridge in a pear tree.

The text will be printed to STDOUT unless there is an -o or --outfile argument, in which case the text should be placed inside a file with the given name. Note that there should be 113 lines of text for the entire song:

$ ./twelve_days.py -o song.txt
$ wc -l song.txt
     113 song.txt

In this exercise, you will

13.1 Writing twelve_days.py

13.1.1 Counting

13.1.2 Creating the ordinal value

13.1.3 Making the verses

13.1.4 Using the verse() function

13.1.5 Printing

13.1.6 Time to write

13.2 Solution

13.3 Discussion

13.3.1 Making one verse

13.3.2 Generating the verses

13.3.3 Printing the verses

13.4 Going further

Summary

sitemap