answer.
Ask question
Login Signup
Ask question
All categories
  • English
  • Mathematics
  • Social Studies
  • Business
  • History
  • Health
  • Geography
  • Biology
  • Physics
  • Chemistry
  • Computers and Technology
  • Arts
  • World Languages
  • Spanish
  • French
  • German
  • Advanced Placement (AP)
  • SAT
  • Medicine
  • Law
  • Engineering
prohojiy
2 months ago
4

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 mes

sages 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

Computers and Technology
1 answer:
8_murik_8 [964]2 months ago
7 0

Answer:

Aquí está el programa en Python:

def crop(message, k): # se define una función que toma una cadena de mensaje y un límite k como parámetros

   if len(message) <= k: # si la longitud del mensaje es menor o igual que k

       return message #retorna el mensaje tal cual

   else: #si la longitud del mensaje supera el límite

       return ' '.join(message[:k+1].split(' ')[0:-1])   # corta el mensaje

#las líneas siguientes se utilizan para probar el funcionamiento de la función anterior

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:

Este método toma un mensaje y un límite de k caracteres como parámetros y devuelve el mensaje recortado.

La instrucción if len(message) <= k: verifica si la longitud del mensaje es menor o igual al límite k. Por ejemplo, si k es Why not y k es 100, la condición resulta falsa. Sin embargo, si se cumple, la función retorna el mensaje completo.

Si la condición anterior es falsa, se ejecuta la parte else que contiene la siguiente sentencia:

       return ' '.join(message[:k+1].split(' ')[0:-1])          

Esta sentencia utiliza el método split() para dividir el mensaje desde k+1 en una lista de palabras usando el espacio como separador.

Por ejemplo, si el mensaje es Codibility We test coders y k=14 y entonces k+1=15

Entonces message[:k+1] corresponde a la subcadena :

Codibility We

message[:k+1].split(' ') separa el mensaje[:k+1] que es Codibility We

en una lista de palabras individualmente como:

['Codibility', 'We', 't']    

Observa que hay una 't', que es el primer carácter de test, que supera el límite k y corta la palabra test. Así que aplicamos un corte aquí

[0:-1] indica desde el inicio de message[:k+1] hasta un elemento (el último de la subcadena) se elimina de la lista (especificado por -1)

Ahora, message[:k+1].split(' ')[0:-1]  da:

['Codibility', 'We']

Finalmente, .join concatena todas las palabras en la lista en una cadena usando un separador vacío como carácter.

Así, la sentencia:

        return ' '.join(message[:k+1].split(' ')[0:-1])          

produce el siguiente resultado:

Codibility We  

You might be interested in
Return 1 if ptr points to an element within the specified intArray, 0 otherwise.
Rzqust [1037]

Answer:

int withinArray(int * intArray, int size, int * ptr) {

      if(ptr == NULL) // if ptr is NULL return 0

            return 0;

      // if the size of intArr is zero

      if(size == 0)

          return 0; // not found

  else  

          {

            if(*(intArray+size-1) == *(ptr)) // check if (size-1)th element equals ptr

                   return 1; // return positive indication

            return withinArray(intArray, size-1,ptr); // call function recursively with size-1 elements

         }

}

Explanation:

This is the complete part of the program.

4 0
22 days ago
Run a Monte Carlo simulation on this vector representing the countries of the 8 runners in this race:
zubka84 [1067]

Answer:

Explanation:

# Execute a Monte Carlo simulation 10k times

B <- 10000

results <- replicate(B, {

 winners <- sample(runners, 3)

 (winners[1] %in% "Jamaica" & winners[2] %in% "Jamaica" & winners[3] %in% "Jamaica")

})

mean(results)

4 0
28 days ago
Write measurable performance objectives.Suppose that a trainer has identified as a generalgoal for a training module,"Able to fo
8_murik_8 [964]

Response:

Damon ComSci 037-0945 Activity 11-3 Formulate measurable performance objectives.... Imagine a trainer has set a broad aim for a training module, saying, “Able to format printed output in accordance with a specification sheet.” First, revise this goal statement to specify a quantifiable performance objective.

Explanation:

6 0
1 month ago
A video conferencing application isn't working due to a Domain Name System (DNS) port error. Which record requires modification
Rzqust [1037]

Answer:

Service record (SRV)

Explanation:

Service records, known as SRV records, contain information defining aspects of the DNS like port numbers, server details, hostnames, priority, weight, and the IP addresses of designated service servers.

The SRV record serves as a valuable reference for locating specific services, as applications needing those services will search for the corresponding SRV record.

When configured, the SRV provides the necessary ports and personal settings for a new email client; without this, the parameters within the email client will be incorrect.

8 0
2 months ago
Dan is a Civil Engineer for a company that builds nuclear power plants throughout the world. Which best describes the places he
oksian1 [950]
In a lab... C 
4 0
1 month ago
Read 2 more answers
Other questions:
  • Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
    5·1 answer
  • Light travels at 3 × 108 meters per second. A light-year is the distance a light beam travels in one year.Write a PYTHON program
    14·1 answer
  • Sarah works in a coffee house where she is responsible for keying in customer orders. A customer orders snacks and coffee, but l
    13·2 answers
  • Assume that the following variables have been properly declared and initialized.
    12·1 answer
  • RADIAC instruments that operate on the ionization principle are broken down into three main categories based on what?
    15·1 answer
  • Which generation of programming languages provides programmers with a visual environment for coding programs?
    12·1 answer
  • Factoring of integers. Write a python program that asks the user for an integer and then prints out all its factors. For example
    13·1 answer
  • If a cell reference is c6, this cell is in the sixth column and the third row. true or false
    11·2 answers
  • HELP ME ON THIS PLEASE ILL GIVE BRAINLY!!!! If U GET IT RIGHT !!!
    10·1 answer
  • Suggest how the following requirements might be rewritten in a quantitative way. You may use any metrics you like to express the
    7·1 answer
Add answer
Login
Not registered? Fast signup
Signup
Login Signup
Ask question!