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
6. Write pseudo code that will perform the following. a) Read in 5 separate numbers. b) Calculate the average of the five number
zubka84 [1067]

Answer:

Pseudo CODE

a)

n= Input “Enter 5 integer values”

b)

sum=0.0

For loop with i ranging from 0 to 5

Inside loop sum=n[i]+sum

Outside loop avg=sum/5

Print avg

c)

small=n[0] # assume initial number is the smallest

large=n[0] # assume initial number is the largest

For loop with i ranging from 0 to 5

Inside loop if n[i]<small # check if current number is smaller than small

Inside if Then small=n[i]

Inside loop if n[i]>large # check if current number is larger than large

Inside if then large=n[i]

Print small

Print large

d)

print avg

print small

print large

8 0
1 month ago
When performing actions between your computer and one that is infected with a virus which of the following offers no risk becomi
Natasha_Volkova [1026]

Please provide your answer choices

thank you:)

6 0
1 month ago
Write a generator function named count_seq that doesn't take any parameters and generates a sequence that starts like this: 2, 1
zubka84 [1067]

Response:

#code (count_seq.py)

def count_seq():

   n='2'

   while True:

       yield int(n)

       next_value=''

       while len(n)>0:

           first=n[0]

           count=0

     

           while len(n)>0 and n[0]==first:

               count+=1

               n=n[1:]

           next_value+='{}{}'.format(count,first)

       n=next_value

if __name__ == '__main__':

   gen=count_seq()

   for i in range(10):

       print(next(gen))

Clarification:

  • Begin with the number 2. Utilize a string for easier manipulation rather than integers.
  • Engage in an infinite loop.
  • Yield the current integer value of n.
  • Continue looping until n becomes an empty string.
  • Repeat as long as n has content and the first digit matches the leading digit.
  • Concatenate the count and the first digit to form next_value.
3 0
21 day ago
Xem tập các tiến trình sau đây, với thời gian cần chạy ở cột Burst Time được cho ở đơn vị mili giây.
maria [1035]
I can't comprehend this language; otherwise, I would assist you.
3 0
1 month ago
You are a police officer trying to crack a case. You want to check whether an important file is in the evidence room. Files have
Harlamova29_29 [1022]

Answer:

Since RANDY operates randomly, any file within the specified index range will have the recurrence relation as follows:

T(n) = T(n-i) + O(1)

Here, the probability is 1/n, where i can vary between 1 and n. The variable n in T(n) denotes the size of the index range, which will subsequently reduce to (n-i) in the following iteration.

Given that i is probabilistically distributed from 1 to n, the average case time complexity can then be expressed as:

T(n) = \sum_{i=1}^{n}\frac{1}{n}T(n-i) + O(1) = T(n/2)+O(1)

Next, solving T(n) = T(n/2) + O(1)

yields T(n) = O(log n).

Thus, the complexity of this algorithm is O(log n).

It should be noted that this represents the average time complexity due to the algorithm's randomized nature. In the worst-case scenario, the index range may only decrease by 1, resulting in a time complexity of O(n) since the worst-case scenario would be T(n) = T(n-1) + O(1).

3 0
1 month ago
Read 2 more answers
Other questions:
  • 3.14 LAB: Input and formatted output: Caffeine levels A half-life is the amount of time it takes for a substance or entity to fa
    9·1 answer
  • Two middle-order batsmen are compared based on their performance in their previous cricket match.
    7·1 answer
  • Imagine you were using some of our pixelation tools to create an image and you posted it online for your friends to see - but, a
    11·1 answer
  • Knowledge flows from the information that has been generated. Which of the following does not necessarily flow from information
    15·1 answer
  • 3. Megan and her brother Marco have a side business where they shop at flea markets, garage sales, and estate
    9·1 answer
  • Meadowdale Dairy Farm sells organic brown eggs to local customers. It charges $3.25 for a dozen eggs, or 45 cents for individual
    6·1 answer
  • Which generation of programming languages provides programmers with a visual environment for coding programs?
    12·1 answer
  • Allison wants to use equations to simplify the process of explaining something to the Sales team, but the default eq
    8·2 answers
  • HELP ME ON THIS PLEASE ILL GIVE BRAINLY!!!! If U GET IT RIGHT !!!
    10·1 answer
  • Language levels have a direct influence on _______________
    10·1 answer
Add answer
Login
Not registered? Fast signup
Signup
Login Signup
Ask question!