Bài toán "99 Bottles of Beer"
Bài toán này dựa trên một bài hát dân gian tiếng Anh có tên là "99 Bottles of Beer on the Wall". Nội dung bài hát (và cũng là nội dung của bài toán) như sau:
-
Bắt đầu với 99 chai bia trên tường.
-
Mỗi lần, bạn hát một đoạn như sau:
99 bottles of beer on the wall, 99 bottles of beer.
Take one down and pass it around, 98 bottles of beer on the wall.
-
Sau đó lặp lại với 98, 97, ... cho đến khi còn 0 chai:
No more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.
Giải pháp đầu tiên
class BottlesOfBeer:
def song(self):
return self.verses(99, 0
def verses(self, hi, lo):
return '\n'.join(self.verse(n) for n in range(hi, lo - 1, -1))
def verse(self, n):
return (
f'{"No more" if n == 0 else n} bottle{"s" if n != 1 else ""}'
f' of beer on the wall, '
f'{"no more" if n == 0 else n} bottle{"s" if n != 1 else ""} of beer.\n' +
(f'Go to the store and buy some more, ' if n == 0 else f'Take {"one" if n != 1 else "it"} down and pass it around, ') +
f'{"99" if n - 1 < 0 else ("no more" if n - 1 == 0 else n - 1)} bottle{"s" if n - 1 != 1 else ""}'
f' of beer on the wall.\n'
)
Đoạn code trên thực hiện một thủ thuật gọn gàng. Nó có thể cô đọng đến mức không ai có thể hiểu được trong khi vẫn giữ lại rất nhiều sự trùng lặp. Mã này khó hiểu vì nó không nhất quán và trùng lặp, và vì nó chứa các khái niệm ẩn mà nó không đặt tên. Vì nhúng rất nhiều logic vào chuỗi câu thơ.