Exercism: Twelve Days (Python)

打印一首歌的歌词。主要是分开有规律和需要单独处理的部分,例如 1)开头的一句, 2)中间的句子,和3)最后一句。先单独处理好一遍的歌词,最后在给多变的歌词套个循环。

看了其他人写的,没什么更简便的方法。有一个人用了 num2words,之前不知道这个package。

FIRST_LINE = "On the {} day of Christmas my true love gave to me: "
BODY = [
    "a Partridge in a Pear Tree",
    "two Turtle Doves",
    "three French Hens",
    "four Calling Birds",
    "five Gold 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",
]
DAYS = ["first", "second", "third", "fourth", "fifth", "sixth",
        "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"]


def recite(start_verse, end_verse):

    def recite_one(verse):
        show_end = "" if verse == 1 else "and "
        for i in range(verse-1, verse):
            head = FIRST_LINE.format(DAYS[i])
            body = "".join([f"{BODY[j]}, " for j in range(verse-1, 0, -1)])
            tail = f"{show_end}{BODY[0]}."
        return f"{head}{body}{tail}"

    return [recite_one(verse) for verse in range(start_verse, end_verse+1)]

评论

此博客中的热门博文

拜厄练习曲44, 45

拜厄练习曲38, 39