Program to find k partitions after truncating sentence using Python


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 −

Example

 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))

Input

"Coding challenges are really helpful for students", 5

Output

Coding challenges are really helpful

Updated on: 29-May-2021

56 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements