\$\begingroup\$
\$\endgroup\$
3
The function receives a string containing a sentence. Its goal is to shorten every word in it to a length of 4 characters until the string is shorter than 38 characters and return.
The 38 characters max length is mandatory and must be reached with the least amount of deletion possible.
Here is what I've done:
# reduces each word to a lenght of 4
def shorten_words(string):
i = 0
j = 0
while(len(string) > 38 and i < len(string)):
array = list(string)
if(array[i] != ' ' and array[i] != '-'):
j += 1
else:
j = 0
if(j > 4):
array[i] = ''
i -= 1
i += 1
string = ''.join(array)
return(string)
I feel like the list/join method is inefficient and would like to know how I could improve this function
Toby Speight
87.1k14 gold badges104 silver badges322 bronze badges
asked Nov 27, 2018 at 8:46
-
2\$\begingroup\$ The post says, "its goal is to shorten every word in it to a length of 4 characters" but if the string is 38 characters or shorter, then the code returns the string unchanged. Could you fix the description of the problem please? \$\endgroup\$Gareth Rees– Gareth Rees2018年11月27日 09:11:20 +00:00Commented Nov 27, 2018 at 9:11
-
\$\begingroup\$ @GarethRees this has been done, thanks for letting me know \$\endgroup\$Comte_Zero– Comte_Zero2018年11月27日 10:17:22 +00:00Commented Nov 27, 2018 at 10:17
-
\$\begingroup\$ What do you mean by "least amount of deletion" though? Is there a requirement that each word in the end should be as close in length as possible? If not the problem is much simpler. \$\endgroup\$l0b0– l0b02018年11月27日 18:36:03 +00:00Commented Nov 27, 2018 at 18:36
1 Answer 1
\$\begingroup\$
\$\endgroup\$
0
Some suggestions:
- Naming is really important.
string
,array
,i
andj
are not descriptive. After reading the entire function I think they could be renamedsentence
,words
,string_index
andword_length
. - There's no point in adding empty strings to the array - they aren't printed anyway.
- What is the significance of 38? If it's not significant it should be removed, if it is it should be named something like
max_result_length
. - In Python
return
is a simple statement, which means its argument should not be put in parentheses.
lang-py