Answer:
here is the Python program:
def crop(message, k): #function definition which takes a message string and a limit k as parameter
if len(message) <= k: # if length of the message is less or equal to limit k
return message #return the message as it is
else: #if length of message exceeds limit
return ' '.join(message[:k+1].split(' ')[0:-1]) # crops the message
#the following lines are used to test the working of the above function
test1 = crop("Codibility We test coders",14)
test2 = crop("The quick brown fox jumps over the lazy dog",39)
test3 = crop("Why not",100)
print(test1)
print(test2)
print(test3)
Explanation:
The above method take a string of message and limit of k characters as parameters and returns the cropped message.
if statement if len(message) <= k: checks if the length of the message is less than or equal to the limit k. For example k is Why not and limit of k is 100. So this statesmen evaluates to false. However if this statement evaluates to true then the function returns the complete message string as it is.
If the above if condition evaluates to false then the else part executes which has the following statement:
return ' '.join(message[:k+1].split(' ')[0:-1])
This statement contains split() method breaks the message from k+1 into a list of words based on empty space delimiter.
For example if the message is Codibility We test coders and k=14 and k+1=15
Then message[:k+1] is the substring :
Codibility We
message[:k+1].split(' ') statement splits the message[:k+1] i.e. Codibility We
into a list of separated words as:
['Codibility', 'We', 't']
Note that we have 't' the first character of test which exceeds the limit k and also breaks the word test. So we add a slice here
[0:-1] which means from start of message[:k+1] till one word (last substring) removes from the list (specified by -1)
Now the message[:k+1].split(' ')[0:-1] statement gives:
['Codibility', 'We']
Now .join is used to join all the words in a list into a string using a separator character i.e. empty space here
Hence the statement:
return ' '.join(message[:k+1].split(' ')[0:-1])
gives output for the above example:
Codibility We