<p>递归函数是个好主意</p>
<pre><code>def expand_vowels(word):
</code></pre>
<p>如果<code>word</code>中没有通配符,则生成不变的单词并使用<code>return</code>语句来表示递归结束</p>
<pre><code> if '*' not in word: yield word ; return
</code></pre>
<p>如果我们在这里,<code>word</code>中至少有一个<code>'*'</code></p>
<pre><code> for new_word in (word.replace('*', vw, 1) for v in 'aeiou'):
for new2_word in expand_vowels(new_word): yield new2_word
</code></pre>
<p>通过一些简单的测试,很容易把所有这些放在一起</p>
<pre><code>$ cat vow.py
def expand_vowels(word):
if '*' not in word: yield word ; return
for new_word in (word.replace('*', v, 1) for v in 'aeiou'):
for new2_word in expand_vowels(new_word): yield new2_word
for w in ('a', 'a*', 'a**'):
print(list(expand_vowels(w)))
good = ['aei', 'bwe']
for wild in ('a**', 'b**'):
for word in expand_vowels(wild):
if word in good:
print(word, 'is in the good words')
break
else:
print(wild, 'doesn\'t generate a good word')
</code></pre>
<pre class="lang-none prettyprint-override"><code>$ python vow.py
['a']
['aa', 'ae', 'ai', 'ao', 'au']
['aaa', 'aae', 'aai', 'aao', 'aau', 'aea', 'aee', 'aei', 'aeo', 'aeu', 'aia', 'aie', 'aii', 'aio', 'aiu', 'aoa', 'aoe', 'aoi', 'aoo', 'aou', 'aua', 'aue', 'aui', 'auo', 'auu']
aei is in the good words
b** doesn't generate a good word
$
</code></pre>