Program to find k partitions after truncating sentence using Python

Suppose we have a sentence s containing English words separated by single spaces with no leading or trailing spaces. We also have a value k. We need to find only the first k words after truncating the sentence.

So, if the input is like s = "Coding challenges are really helpful for students" and k = 5, then the output will be "Coding challenges are really helpful".

Algorithm

To solve this, we will follow these steps ?

  • Split the sentence s by spaces to get individual words

  • Take the first k words from the words array

  • Join these words back with spaces and return the result

Example

Let us see the following implementation to get better understanding ?

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

The output of the above code is ?

Coding challenges are really helpful

How It Works

The function works by using Python's string methods:

  • split() ? Splits the sentence into a list of words

  • words[:k] ? Takes only the first k elements using list slicing

  • join() ? Combines the selected words back into a string with spaces

Edge Cases

Let's test with different scenarios ?

def solve(s, k):
    words = s.split()
    return " ".join(words[:k])

# Test cases
print(solve("Hello world", 1))  # Only first word
print(solve("Python is awesome", 5))  # k greater than word count
print(solve("Single", 1))  # Single word
Hello
Python is awesome
Single

Conclusion

This solution efficiently truncates a sentence to the first k words using split() and join() methods. The time complexity is O(n) where n is the length of the sentence.

Updated on: 2026-03-25T20:53:10+05:30

164 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements