Program to find k partitions after truncating sentence using Python

PythonServer Side ProgrammingProgramming

Suppose we have sentence s where some English words are present, that are separated by a single space with no leading or trailing spaces. We also have another value k. We have to find only the first k words after truncating.

So, if the input is like s = "Coding challenges are really helpful for students" k = 5, then the output will be True (See the image)

To solve this, we will follow these steps −

  • words := split s by spaces

  • join first k letters from words array by separating spaces and return

Let us see the following implementation to get better understanding −


 Live Demo

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
Updated on 29-May-2021 14:16:46