Arrange string based on numbers

1

I'm learning to program in Python and for this I make challenges that I encounter on the internet in order to better fix each method, function etc. This challenge consists of creating a function that orders 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 for " is2 Thi1s T4est 3a" " but it did not work para 'Fo1r the2 4of g3ood pe6ople th5e' .

I can not find the problem in the code.

    
asked by anonymous 10.03.2016 / 14:53

1 answer

1

The problem with your code is basically the fact that you enter values in the list in positions that do not yet exist

>>> my_list = []
>>> my_list.insert(5, 'foo')
>>> my_list.insert(4, 'bar')
>>> my_list
['foo', 'bar']

Your first test worked in the order the text was entered

>>> my_list = []
>>> my_list.insert(1, 'is2')
>>> my_list.insert(0, 'Thi1s')
>>> my_list.insert(3, 'T4est')
>>> my_list.insert(2, '3a')
>>> my_list
['Thi1s', 'is2', '3a', 'T4est']

Any different order could give an unexpected result. There is a simpler way to do this, just use the builtin function sorted :

def order_key(word):
    for char in word:
        if char.isdigit():
            return char


print(sorted('Ess1a 4vida 3a 2é re5al'.split(), key=order_key))

The parameter key of the function sorted determines what will be the criteria of organization of the list, in case I created a function that returns the number inside the word.

Another detail, be careful with this str(range(1, 10) stretch in python2 the result would be:

>>> str(range(1, 10))
'[1, 2, 3, 4, 5, 6, 7, 8, 9]'

Already in python3

>>> str(range(1, 10))
'range(1, 10)'

I do not think this is what you were looking for, maybe it was:

>>> map(str, range(1, 10))
['1', '2', '3', '4', '5', '6', '7', '8', '9']

The buitin function map applies a particular function to all items in an iteravel. Just be careful because in python3 the map function returns a generator.

    
10.03.2016 / 17:58