2
I am learning to program in Python and for this I make challenges that I find on the internet in order to better fix each method, function etc This challenge consists of creating a function that sorts a string in which each word has a number of 1-9 in the middle according to the number contained without removing it from the string.
Ex: "Ess1a 4vida 3a 2é re5al" após a função "Ess1a 2é 3a 4vida re5al"
The code is as follows::
def order(sentence):
new_sent = []
for word in sentence.split():
char = list(word)
for c in char:
if c in str(range(1, 10)):
new_sent.insert(int(c)-1, word)
return " ".join(new_sent)
When testing the code it worked to "is2 Thi1s T4est 3a"
but it didn’t work para 'Fo1r the2 4of g3ood pe6ople th5e'
.
I can’t find the problem in the code.
Thank you! I was in doubt if inserting values in a position that was still non-existent was the problem. But the question remains: what made the code correctly order the first test but not the second? I will take this hint of the map in another code that was also giving problem, probably this was the problem.
– JP Kato
I edited the answer added the explanation of why the first test worked, from a look. If it has helped, please indicate the answer as the chosen one and/or an up in it.
– drgarcia1986