使用 Python 编写程序,在截断句子后查找 k 个分区

pythonserver side programmingprogramming更新于 2025/5/27 1:16:17

假设我们有句子 s,其中存在一些英文单词,这些单词由一个空格分隔,没有前导或尾随空格。我们还有另一个值 k。我们只需在截断后找到前 k 个单词。

因此,如果输入为 s = "Coding challenges are really helpful for students" k = 5,则输出将为 True(参见图片)

为了解决这个问题,我们将遵循以下步骤 −

  • words := split s by space

  • 通过分隔空格连接 words 数组中的前 k 个字母并返回

让我们看看下面的实现以便更好地理解 −

示例

def solve(s, k):
   words = s.split()
   return " ".join(words[:k])
s = "Coding challenges are really helpful for students"
k = 5
print(solve(s, k))

输入

"Coding challenges are really helpful for students", 5

输出

Coding challenges are really helpful

相关文章


有用资源