First of all, remember that python has much more efficient sorting algorithms already implemented in the language, simply calling a function to sort:
entrada = ''.join(sorted(entrada))
But to answer your question: yes, lists are mutable, you can convert your string into a list:
entrada = "32415"
entrada = list(entrada)
Your sorting algorithm has some problems, it seems that you are trying to use the "bubble method", however you need to return to position whenever there is change, in which case it would be better to use the while
instead of for
:
i = 1
while i < len(entrada):
if entrada[i] < entrada[i-1]:
entrada[i], entrada[i-1] = entrada[i-1], entrada[i]
i = max(1, i - 1)
else:
i += 1
Then at the end you can convert the result back to string using the join
:
entrada = ''.join(entrada)
print(entrada)
The result:
12345
Two tips: 1) you do not need to convert the character to string at the end, since it is already a character; 2) change the variable name, have
entrada
as a result is very confusing, ideally leave unchanging input and set others to the result.– Woss
Oops, thank you so much for the tip! I’m still beginner and I will follow this yes for sure :D
– Gau