Skip to content

Problem 3: Distribute Matcha Parfait (200pts)

Problem

Kaname Rāna, a member of the band MyGO!!!!!, loves matcha parfaits(抹茶芭菲) very much and enjoys distributing them to others (such as Chihaya Anon, Togawa Sakiko, Nagasaki Soyo, Wakaba Mutsumi, etc.).

alt text

However, Rāna has particular habits:

  1. She must give at least 1 parfait to each member.
  2. She wants to see different distribution methods.

As a laid-back cat, Rāna doesn't want to think hard about how to distribute them herself, so she has entrusted the task of matcha parfait distribution to students studying SICP.

You need to implement the generator function distribute_parfait, which takes as input the number of matcha parfaits n and the positive number of characters k

It yields all distribution methods and each distribution method is a list of length k, indicating the number of parfaits each member receives. When there is no distribution methods available, yield nothing.

Kaname Rāna(要乐奈),MyGO!!!!! 乐队的成员,非常喜欢抹茶芭菲,并且乐于将它们分发给其他人(例如千早爱音、丰川祥子、长崎爽世、若叶睦等)。

然而,Rāna 有一些特殊的习惯:

  1. 她必须给每位成员至少 1 个芭菲。
  2. 她想看到不同的分配方法。

作为一个悠闲的猫,Rāna 不想自己辛苦地思考如何分配,所以她把分配抹茶芭菲的任务委托给了学习 SICP 的学生。

你需要实现生成器函数 distribute_parfait,它接受抹茶芭菲的数量 n 和角色的正数 k 作为输入。

它产出所有分配方法,每种分配方法是一个长度为 k 的列表,表示每位成员收到的芭菲数量。当没有可用的分配方法时,不产出任何内容。

def distribute_parfait(n, k):
    """Generates all distribution methods of the given number of parfaits n and positive number of members k. 
    each distribution method is a list of length k, indicating the number of parfaits each member receives.

    >>> methods = distribute_parfait(1, 1)
    >>> type(methods)
    <class 'generator'>
    >>> next(methods)
    [1]
    >>> try: #this piece of code prints "No more distribution methods!" if calling next would cause an error
    ...     next(methods)
    ... except StopIteration:
    ...     print('No more distribution methods!')
    No more distribution methods!
    >>> sorted(distribute_parfait(2, 2)) # Returns a sorted list containing elements of the generator
    [[1, 1]]
    >>> sorted(distribute_parfait(4, 3))
    [[1, 1, 2], [1, 2, 1], [2, 1, 1]]
    >>> sorted(distribute_parfait(5, 2))
    [[1, 4], [2, 3], [3, 2], [4, 1]]
    """
    "*** YOUR CODE HERE ***"

Hints

Hint1: The parfaits are identical, but the members are distinct (distributions [2,1] and [1,2] are considered different)

Hint2: There is no need to use some advanced non-recursive algorithms, which you may find on the Internet. Recursion is sufficient.

  • 丰川祥子是 Togawa Sakiko 而不是 Toyogawa Saki。

  • 芭菲是相同的,但成员是不同的(分配 [2,1] 和 [1,2] 被认为是不同的)

  • 没有必要使用一些你在网上可能找到的高级非递归算法,递归就足够了。

  • 你可能需要一个辅助函数。

  • 你可能需要进行 deepcopy,当然也可能不需要。

Solutions