DEV Community

Hai Vu
Hai Vu

Posted on Edited on

Twelve Days of Christmas Part Two

img

A few years back, I posted a fun 12-line Python script which generates the lyric for the "Twelve Days of Christmas" song. It is now time to revisit the old topic and do it differently, just for fun.

The goal this time is not to wrap everything neatly in 12 lines of code, but rather to come up with a different way to get the job done. Here it is:

from itertools import accumulate

def combine_gifts(old, new):
    return f"{new}\n  {old}"

DAYS = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelveth"]
VERSES = [
    "A partridge in a pear tree",
    "Two turtle doves, and",
    "Three French hens",
    "Four calling birds",
    "Five golden rings",
    "Six geese a-laying",
    "Seven swans a-swimming",
    "Eight maids a-milking",
    "Nine ladies dancing",
    "Ten lords a-leaping",
    "Eleven pipers piping",
    "Twelve drummers drumming",
]

for day, gifts in zip(DAYS, accumulate(VERSES, combine_gifts)):
    print(f"On the {day} day of Christmas, my true love sent to me\n  {gifts}\n")
Enter fullscreen mode Exit fullscreen mode

One challenge I faced in both the first solution and this was how to place the word "and" between the first and the second day. This "and" was needed for the last 11 days, but not the first. After thinking through, I found the solution: add the word "and" at the end of the second day's gift instead of prefixing the first day.

In order to generate a list of gifts for each day, this time, I use a lesser-known function: itertools.accumulate(). In the first iteration, it generates the first day's gift. In the second day, it generates the second day's gift, plus the first. On the third day, it generates the third day's gift, plus previous days' gifts, and so on.

The accumulate() function has very little use, at least for me, but now it seems to be the right occasion for its usage.

Do you have something fun like this one? Please share.

Merry Christmas of 2026!

Top comments (0)