Change string Python

0

I am doing a program to sort the entered numbers (I can not simply use a sort algorithm), searching vi that can not change strings in python, have any way to do this? Or maybe use list instead of string?

entrada = "32415"

for i in range(entrada):
    if entrada[i] > entrada[i+1]:
        aux = entrada[i]
        entrada[i] = entrada[i+1]
        entrada[i+1] = aux

print(entrada) 
    
asked by anonymous 18.09.2018 / 03:31

2 answers

3

First of all, remembering that python has much more efficient sorting algorithms already implemented in the language, just call a function to sort:

entrada = ''.join(sorted(entrada))

But, answering your question: yes, lists are mutable, you can convert your string to list:

entrada = "32415"
entrada = list(entrada)

Your sorting algorithm has some problems, it looks like you're trying to use the "bubble method", however you need to get back to wherever there is a trade, in which case it would be best to use 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 in the end you can convert the result back to string using join :

entrada = ''.join(entrada)
print(entrada)

The result:

12345
    
18.09.2018 / 05:22
1

Hello, how are you? : D
I do not know if you are studying algorithms for sorting or want a practical solution of Python, but I will follow the second option. To sort your entry variable, one possibility could be as follows:

entrada = '32415'
# Nos dois próximos comandos a string vai virar uma lista.
# Em ordem crescente.
entrada = sorted(entrada)
# Ordem decrescente.
entrada = sorted(entrada, reverse=True)
# Converter de volta para string.
entrada = ''.join(str(a) for a in entrada)

I do not know if this is what you want, but I hope so: D

    
18.09.2018 / 04:12