Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
sby spaces to get individual wordsTake the first
kwords from the words arrayJoin 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 wordswords[:k]? Takes only the firstkelements using list slicingjoin()? 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.
