擅长:python、mysql、java
<p>不允许使用<code>str.split</code>。如果可以的话,答案就是:</p>
<pre><code>def kth_word(s, k):
return s.split()[k]
</code></pre>
<p>但是如果你能写一个函数来做<code>str.split</code>所做的事情,你可以改为调用它。当然,这也说明您理解了任务测试的所有内容,如何在字符串上循环,执行逐字符操作,等等。在</p>
<p>您可以编写一个只包含Python特性的版本,这些特性通常在第一周就已经教授过了:</p>
^{pr2}$
<p>如果您了解其他Python功能,可以通过以下几种方式改进:</p>
<ul>
<li>将<code>current</code>构建为<code>list</code>,而不是<code>str</code>和{<cd6>}。在</li>
<li>将那些<code>append</code>调用改为<code>yield</code>,这样它就可以懒洋洋地拆分字符串(甚至比<code>str.split</code>更好)。在</li>
<li>使用<code>str.find</code>或<code>str.index</code>或<code>re.search</code>查找下一个空格,而不是逐个字符搜索。在</li>
<li>将空间查找部分抽象到一个通用生成器中,或者,一旦您意识到您想要的,就可以在<code>itertools</code>中找到该函数。在</li>
<li>添加我们在<code>str.split</code>中缺少的所有功能,例如传递自定义分隔符而不是打断任何空白的功能。在</li>
</ul>
<p>但我认为即使是基本版本,假设你理解它并能解释它的工作原理,也足以让你的作业得个A。在</p>
<p>而且,更重要的是,你在练习解决问题的最佳方法:把它们简化成更简单的问题。<code>split</code>实际上比<code>kth_word</code>更容易写,但是一旦你写了<code>split</code>,<code>kth_word</code>就变得微不足道了。在</p>