3

这是 Berkeley Logo 中一个简短但完整的程序:

to choices :menu [:sofar []]
if emptyp :menu [print :sofar stop]
foreach first :menu [(choices butfirst :menu sentence :sofar ?)]
end

这就是你如何使用它。你输入

choices [[small medium large]
         [vanilla [ultra chocolate] lychee [rum raisin] ginger]
         [cone cup]]

和徽标回复

    small vanilla cone
    small vanilla cup
    small ultra chocolate cone
    small ultra chocolate cup
    small lychee cone
    small lychee cup
    small rum raisin cone
    small rum raisin cup
    small ginger cone
    small ginger cup
    medium vanilla cone
    medium vanilla cup
    medium ultra chocolate cone
    medium ultra chocolate cup
    medium lychee cone
    medium lychee cup
    medium rum raisin cone
    medium rum raisin cup
    medium ginger cone
    medium ginger cup
    large vanilla cone
    large vanilla cup
    large ultra chocolate cone
    large ultra chocolate cup
    large lychee cone
    large lychee cup
    large rum raisin cone
    large rum raisin cup
    large ginger cone
    large ginger cup

资料来源:http ://www.eecs.berkeley.edu/~bh/logo-sample.html

你会如何在 python 中做到这一点?

4

1 回答 1

7

像往常一样,该itertools模块提供了一个解决方案:

>>> choices = [["small", "medium", "large"],
...            ["vanilla", "ultra chocolate", "lychee", "rum raisin", "ginger"],
...            ["cone", "cup"]]
>>> from itertools import product
>>> print("\n".join(" ".join(item) for item in product(*choices)))
small vanilla cone
small vanilla cup
small ultra chocolate cone
small ultra chocolate cup
small lychee cone
small lychee cup
small rum raisin cone
small rum raisin cup
small ginger cone
small ginger cup
medium vanilla cone
<etc...>
于 2013-06-19T17:13:25.407 回答