<p>我根本不懂C,但我可以解释Python代码是如何工作的。在</p>
<pre><code>@memo
def segment(text):
"Return a list of words that is the best segmentation of text."
if not text: return []
candidates = ([first]+segment(rem) for first,rem in splits(text))
return max(candidates, key=Pwords)
</code></pre>
<p>第一条线</p>
^{pr2}$
<p>是一个<a href="http://docs.python.org/glossary.html#term-decorator" rel="nofollow">decorator</a>。这将导致函数(在后面的行中定义)被包装在另一个函数中。装饰器通常用于过滤输入和输出。在本例中,根据它所包装的函数的名称和角色,我认为这个函数<a href="http://en.wikipedia.org/wiki/Memoization" rel="nofollow">memoizes</a>调用<code>segment</code>。在</p>
<p>下一步:</p>
<pre><code>def segment(text):
"Return a list of words that is the best segmentation of text."
if not text: return []
</code></pre>
<p>正确声明函数,给出<a href="http://docs.python.org/glossary.html#term-docstring" rel="nofollow">docstring</a>,并设置此函数递归的终止条件。在</p>
<p>接下来是最复杂的一行,也可能是给你带来麻烦的那一行:</p>
<pre><code> candidates = ([first]+segment(rem) for first,rem in splits(text))
</code></pre>
<p>外圆括号与<code>for..in</code>构造相结合,创建一个<a href="http://docs.python.org/glossary.html#term-generator-expression" rel="nofollow">generator expression</a>。这是迭代序列的有效方法,在本例中是<code>splits(text)</code>。生成器表达式是一种紧凑的for循环,可以产生值。在这种情况下,这些值将成为迭代<code>candidates</code>的元素。”Genexps“类似于<a href="http://en.wikipedia.org/wiki/List_comprehension" rel="nofollow">list comprehensions</a>,但是通过不保留它们产生的每个值来实现更高的内存效率。在</p>
<p>因此,对于<code>splits(text)</code>返回的迭代中的每个值,生成器表达式都会生成一个列表。在</p>
<p>来自<code>splits(text)</code>的每个值都是<code>(first, rem)</code>对。在</p>
<p>每个生成的列表都以对象<code>first</code>开头;这是通过将<code>first</code>放在列表文本中来表示的,即<code>[first]</code>。然后将另一个列表添加到其中;第二个列表由对<code>segment</code>的递归调用确定。在Python中添加列表将它们串联起来,即<code>[1, 2] + [3, 4]</code>给出{<cd13>}。在</p>
<p>最后,在</p>
<pre><code> return max(candidates, key=Pwords)
</code></pre>
<p>递归确定的列表<code>iteration</code>和一个键函数被传递给<code>max</code>。对迭代中的每个值调用key函数,以获取用于确定该列表在迭代中是否具有最高值的值。在</p>