Question

In: Computer Science

There is a forum that has a limit of K characters per entry. In this task...

There is a forum that has a limit of K characters per entry. In this task your job is to implement an algorithm for cropping messages that are too long. You are given a message, consisting of English alphabet letters and spaces, that might be longer than the limit. Your algorithm should crop a number of words from the end of the message, keeping in mind that: • it may not crop away part of a word; • the output message may not end with a space; • the output message may not exceed the K-character limit; the output message should be as long as possible. This means that, in some cases, the algorithm may need to crop away the entire message, outputting an empty string. For example, given the text: "Codility We test coders" With K = 14 the algorithm should output: "Codility We" Note that: • the output "Codility We te" would be incorrect, because the original message is cropped through the middle of a word; the output "Codility We would be incorrect, because it ends with a space; the output "Codility We test coders" would be incorrect, because it exceeds the K-character limit; the output "Codility' would be incorrect, because it is shorter than the correct output.
Write a function class Solution { public String solution(String message, int k); } which, given a message and an integer K, returns the message cropped to no more than K characters, as described above. Examples: 1. Given message = "Codility We test coders' and K = 14, the function should return "Codility We". 2. Given message = "Why not" and K = 100, the function should return "Why not". 3. Given message = "The quick brown fox jumps over the lazy dog" and K = 39, the function should return "The quick brown fox jumps over the lazy". Assume that: • K is an integer within the range [1..500]; • message is a non-empty string containing at most 500 English alphabet letters and spaces. There are no spaces at the beginning or at the end of message; also there can't be two or more consecutive spaces in message.

Solutions

Expert Solution

Source Code:

def solution(message, k):
    # if k >= len(message) then return original message
    if k >= len(message):
        return message
    # splice the message till length k
    spliced = message[:k]

    # now if in the original message
    # character at index k is a space
    # and the previous character
    # is a alphanumeric then
    # the cut is at perfect place
    # no need to do anything

    if message[k] == ' ' and message[k - 1] != ' ':
        # return spliced
        return spliced
  
    # remove characters until spaces is read
    while len(spliced) > 0 and spliced[-1] != ' ':
        # remove last character
        spliced = spliced[:-1]
  
    # remove all spaces
    while len(spliced) > 0 and spliced[-1] == ' ':
        # remove last character
        spliced = spliced[:-1]
  

    # return the result
    return spliced

### main script for testing
message = "Codality We test coders"
print(solution(message, 14))

message = "Why not"
print(solution(message, 100))

message = "The quick brown fox jumps over the lazy dog"
print(solution(message, 39))

Sample Output:

Note: If you have any related doubts, queries, feel free to ask by commenting down below.

And if my answer suffice your requirements, then kindly upvote.

Happy Learning


Related Solutions

The second weekly assignment for the course is an open forum. In this assignment you task...
The second weekly assignment for the course is an open forum. In this assignment you task is to find an economic news topic and summarize the article in your post. The purpose of this assignment is to give you a free hand in the subject you wish to discover. The news article can come from any widely known news site such as BBC, Bloomberg, CNBC, Fox Business, MarketWatch, Wall Street Journal, etc. If this does not offer you enough options,...
For this task, assume that you have been asked to host a local forum for parents...
For this task, assume that you have been asked to host a local forum for parents of junior high school aged children to discuss the consequences of having sex at an early age. Parents are debating the following topic: A sexuality education unit, at least a week in length, should be included in all grades in all schools. After the debate you are to draft a summary of the conversations. In your paper, provide both the pro and con of...
find the limit as k approaches infinity of [1+(1/10^k)]^10k step by step using the l'hospital
find the limit as k approaches infinity of [1+(1/10^k)]^10k step by step using the l'hospital
Bacterial Endotoxin Limit (EL) is defined as EL=K/m, where K=5 Endotoxin Units (EU) kg of the...
Bacterial Endotoxin Limit (EL) is defined as EL=K/m, where K=5 Endotoxin Units (EU) kg of the body weight or 5 EU/kg/hr;m= maximun bolus dose of a product, and the average human body weight is 70kg.The maximun Valid Dilution (MVD) of a product is equal to (EL x Concentration of the product)/sensivity of the lysate Find the EL for a product whose maximun pediatric dose is 4 mg/ml/kg and concentration is 20mg/ml. Expressthe EL in EU/ml and EU/mg If the sensivitty...
Jane has a Dwelling limit of $500,000 with a deductible of $2000 and a $1million Liability limit.
Jane & Sue both have HO insurance.Jane has a Dwelling limit of $500,000 with a deductible of $2000 and a $1million Liability limit.Sue has a Dwelling limit of $750,000 with a deductible of $5000 and a $2million Liability limit.Sue is visiting Jane and a heavy light fixture falls on her head. Sue’s medical expenses are $10,000 (ambulance, emergency room services, stitches, overnight stay for concussion).Whose policy is ultimately responsible for Sue’s losses?What coverage part of the HO insurance policy is...
The Cosmo K Manufacturing Group currently has sales of $1,400,000 per year. It is considering the...
The Cosmo K Manufacturing Group currently has sales of $1,400,000 per year. It is considering the addition of a new office machine, which will not result in any new sales but will save the company $105,500 before taxes per year over its 5-year useful life. The machine will cost $300,000 plus another $12,000 for installation. The new asset will be depreciated using a modified accelerated cost recovery system (MACRS) 5-year class life. It will be sold for $25,000 at the...
Forum It is costly for businesses to comply with government regulation. More regulation increases per-unit production...
Forum It is costly for businesses to comply with government regulation. More regulation increases per-unit production costs for businesses and shifts the aggregate supply curve to the left. Deregulation will reduce per-unit production costs and shift the AS rightward. Discuss one business and the impact sustained by regulation or deregulation of the industry and how the business model has been affected and/or potential implications.
The speed limit of a road is 65 miles per hour. The speed of a car...
The speed limit of a road is 65 miles per hour. The speed of a car on the highway follows a normal distribution with a mean of 70 and standard deviation of 5. What percent of the distribution breaks the speed limit? The speed limit of a road is 65 miles per hour. The speed of a car on the highway follows a normal distribution with a mean of 70 and standard deviation of 5. A police officer will only...
project k has a cost of 62,125, and its expected nect cash inflwos are 14,000 per...
project k has a cost of 62,125, and its expected nect cash inflwos are 14,000 per year for 8 year . A- The cost of capital is 12 %. What is the project 's npv? B- what is the project 's IRR?
a solid material that has thermal conductivity K in kilowatts per meter-kelvin and temperature given at...
a solid material that has thermal conductivity K in kilowatts per meter-kelvin and temperature given at each point by w(x, y, z) has heat flow given by the vector field F = ?K?wand rate of heat flow across a surface S within the solid given by?K ?? ??S ?w dS. Find the rate of heat flow out of a sphere of radius 1 meter inside a large cube of copper (K=400kilowatts/m-k) with temperature function given by w(x, y, z)=20?5(x2+y2+z2)?C
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT